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

Sql server SQL-如何获取非聚合结果中的重复数?,sql-server,tsql,count,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

假设我有一个表
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\u Number()over(按国家划分)
方法来实现这一点

试试这个:

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

确定执行前行集的分区和排序 应用关联的窗口功能


因此,我们基本上是告诉
计数
记录,但是按照
国家对行进行分组

另一种实现结果的方法:

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

谢谢。我从来不知道聚合函数可以与over子句一起使用。这为我打开了一个巨大的新世界。