SQL计数和组重复

时间:2012-12-19 12:29:13

标签: sql-server

请告知解决问题的最佳方法。

我有一个问题,想弄清楚如何计算表中的重复项,如下所示

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

我想在同一个城市拥有多条重复街道,结果如下:

结果:

Street     | City | Duplicates

avenue 123 | New York | 2
avenue 12  | Chicago | 3

2 个答案:

答案 0 :(得分:20)

使用GROUP BYCOUNTHAVING

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

查看在线工作:sqlfiddle

答案 1 :(得分:3)

尝试:

SELECT street, city, COUNT(*) AS duplicates
FROM yourtable
GROUP BY street, city
HAVING COUNT(*) >1

如果您想要显示没有重复的行,请删除HAVING COUNT(*) > 1