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?
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.
SQL SELECT COUNT() can be clubbed with SQL WHERE clause.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With