Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Count and group duplicates

Tags:

sql-server

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
like image 986
Tom Avatar asked Dec 19 '12 12:12

Tom


People also ask

Does count include duplicates in SQL?

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.

Can we use GROUP BY and count together in SQL?

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.

Can we use count and GROUP BY together?

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.

Does GROUP BY return duplicates?

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.


2 Answers

Use GROUP BY, COUNT and HAVING:

 SELECT Street, City, COUNT(*)
 FROM yourtable
 GROUP BY Street, City
 HAVING COUNT(*) > 1

See it working online: sqlfiddle

like image 134
Mark Byers Avatar answered Oct 01 '22 23:10

Mark Byers


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.

like image 22
xlecoustillier Avatar answered Oct 02 '22 00:10

xlecoustillier