3

I am trying to find, count and report all instances of duplicates entries in a column. Any idea how to do that similar to my attempt below.

SELECT `Id`, COUNT(*) AS `COUNT`
FROM `testproductdata`
WHERE `COUNT` > 1
GROUP BY `Id`
ORDER BY `COUNT` DESC;

I am getting a 1054 error: Unknown column COUNT in where clause.

3

4 Answers 4

6

Use HAVING over WHERE with GROUP BY

SELECT `Id`, COUNT(*) AS `COUNT`
FROM `testproductdata`
GROUP BY `Id`
HAVING  `COUNT` > 1
ORDER BY `COUNT` DESC;

And I suggest to use relevant name for expression on count(*) as total_count than COUNT.

Change query as below:

SELECT `Id`, COUNT(*) AS `total_count`
FROM `testproductdata`
GROUP BY `Id`
HAVING  `total_count` > 1
ORDER BY `total_count` DESC;
2
  • 1
    @EricImprint Hmm, another MySQL oddity (or at least difference) strikes me. Apr 11, 2014 at 23:06
  • It works. Better practice is not to use Reserved words like count as identifiers, though it is an acceptable with no back ticks Apr 11, 2014 at 23:07
1

You should change the where for a having, this should work:

SELECT Id, COUNT(1) AS count
FROM testproductdata
GROUP BY Id
HAVING COUNT(1) > 1
ORDER BY COUNT(1) DESC;
1

Try adding DISTINCT to the query

SELECT * FROM (
SELECT DISTINCT `Id`, (SELECT COUNT(Id) FROM `testproductdata` WHERE `Id`=`Id`) `count`
FROM `testproductdata`
GROUP BY `Id`
HAVING `count` > 1
)
ORDER BY `count` DESC;
3
  • I am getting a 1054 error: Unknown column COUNT in where clause. Apr 11, 2014 at 23:01
  • Why not ?. Oh... hahaha... i see XD --- need to rename the field... also, don't use AS ... just space. Apr 11, 2014 at 23:01
  • 1
    @SanuelJackson Not yet. "In general, clauses used must be given in exactly the order shown in the syntax description. For example, a HAVING clause must come after any GROUP BY clause and before any ORDER BY clause." see manual
    – VMai
    Apr 11, 2014 at 23:08
0

Try this out

select * from 
(SELECT `Id`, COUNT(*) AS `c`
FROM `testproductdata`
group by `Id`)
WHERE `c` > 1
ORDER BY `c` DESC;

or

SELECT `Id`, COUNT(*) AS `c`
FROM `testproductdata`
group by `Id`
having `c` > 1
ORDER BY `c` DESC;
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.