Please advise the best way for solving my problem.
I have a problem figuring out how to count duplicates in table like below
Street | City
avenue 123 | New York
avenue 123 | New York
avenue 20 | New York
avenue 35 | Chicago
avenue 12 | Chicago
avenue 123 | Chicago
avenue 12 | Chicago
avenue 12 | Chicago
I would like to have number of duplicate streets in the same City as result below?
result:
Street | City | Duplicates
avenue 123 | New York | 2
avenue 12 | Chicago | 3
The syntax of the SQL COUNT function: By default, SQL Server Count Function uses All keyword. It means that SQL Server counts all records in a table. It also includes the rows having duplicate values as well.
The GROUP BY statement is often used with aggregate functions ( COUNT() , MAX() , MIN() , SUM() , AVG() ) to group the result-set by one or more columns.
The use of COUNT() function in conjunction with GROUP BY is useful for characterizing our data under various groupings. A combination of same values (on a column) will be treated as an individual group.
GROUP BY only treats two rows as duplicates if all the column values in both the rows are the same. If even a single column value in either of the row is non-matching, they are treated as unique.
Use GROUP BY
, COUNT
and HAVING
:
SELECT Street, City, COUNT(*)
FROM yourtable
GROUP BY Street, City
HAVING COUNT(*) > 1
See it working online: sqlfiddle
Try :
SELECT street, city, COUNT(*) AS duplicates
FROM yourtable
GROUP BY street, city
HAVING COUNT(*) >1
Remove HAVING COUNT(*) > 1
if you want to display lines without duplicates as well.
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