Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building sql query with count() where count() is > 1

If I have a table where there are duplicate IDs, how can I count the number of times the same ID appears in the table and only show records that have a count greater than 1?

I've tried:

SELECT COUNT(ID) AS myCount FROM myTbl
WHERE myCount > 1 GROUP BY ID

But it says myCount is invalid column name. Can someone show me what I'm doing wrong?

like image 715
Nick Rolando Avatar asked Jan 05 '12 22:01

Nick Rolando


People also ask

How does count 1 work in SQL?

In other words, COUNT(1) assigns the value from the parentheses (number 1, in this case) to every row in the table, then the same function counts how many times the value in the parenthesis (1, in our case) has been assigned; naturally, this will always be equal to the number of rows in the table.

Can I use WHERE and count together in SQL?

SQL SELECT COUNT() can be clubbed with SQL WHERE clause.

What is Count * or Count 1 in SQL?

The COUNT (*) function counts the number of rows produced by the query, whereas COUNT (1) counts the number of 1 value. Note, that when you include a literal such as a number or a string in a query, this literal is "appended" or attached to every row that is produced by the FROM clause.


1 Answers

You need to use the HAVING keyword:

SELECT COUNT(ID) AS myCount FROM myTbl
GROUP BY ID
HAVING COUNT(ID) > 1

From MSDN:

Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. HAVING is typically used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause.

like image 183
DaveShaw Avatar answered Sep 20 '22 19:09

DaveShaw