SQL查询:如何统计特定ID记录数并在每行展示该统计值?
解决SQL分组统计问题
你的需求是为每条记录添加其对应id的总记录数,之前的查询因为按name和id分组,导致每个分组仅包含单条数据,所以count(*)结果都是1,无法得到预期值。
可以使用窗口函数来实现,通过PARTITION BY id将数据按id分区,然后统计每个分区的总行数:
declare @tab table(name varchar(10),id int) insert into @tab values ('A',1),('B',1),('C',1),('D',1),('E',2),('F',2) -- 正确查询语句 select name, id, count(*) over (partition by id) as cnt from @tab
执行后会得到你想要的结果:
| name | id | cnt |
|---|---|---|
| A | 1 | 4 |
| B | 1 | 4 |
| C | 1 | 4 |
| D | 1 | 4 |
| E | 2 | 2 |
| F | 2 | 2 |
如果你的SQL版本不支持窗口函数(比如较老的SQL Server版本),也可以用子查询关联的方式实现:
select t.name, t.id, (select count(*) from @tab where id = t.id) as cnt from @tab t
内容的提问来源于stack exchange,提问作者Rahul Aggarwal
相关产品推荐
相关产品推荐

