SQL - 如何获取非聚合结果中的重复数?

时间:2017-11-09 14:31:33

标签: sql-server tsql count

假设我有一张表tb,那么

select * from tb

返回

ID | City     | Country
1  | New York | US     
2  | Chicago  | US     
3  | Boston   | US     
4  | Beijing  | China  
5  | Shanghai | China  
6  | London   | UK     

编写可以返回以下结果的查询的最简单方法是什么?

ID | City     | Country | Count
1  | New York | US      | 3
2  | Chicago  | US      | 3
3  | Boston   | US      | 3
4  | Beijing  | China   | 2
5  | Shanghai | China   | 2
6  | London   | UK      | 1

我能想到的唯一解决方案是

with cte as (select country, count(1) as Count from tb group by country)
select tb.*, cte.Count from tb join cte on tb.Country = cte.Country

但我觉得这还不够简洁。我想知道是否有Duplicate_Number() over (partition by country)之类的东西可以做到这一点。

2 个答案:

答案 0 :(得分:3)

试试这个:

select * 
      ,COUNT(*) OVER (PARTITION BY Country)
from tb

OVER条款

  

确定行之前的行集的分区和排序   应用相关的窗口函数。

因此,我们基本上是告诉COUNT记录,而是按COUNTRY对行进行分组。

答案 1 :(得分:0)

实现结果的另一种方法:

select t1.*, t2.Country_Count from tb t1
join 
    (select country, count(country) Country_Count from tb group by country) t2
on t1.country=t2.country
order by t1.id

SQL HERE