You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

执行后会得到你想要的结果:

nameidcnt
A14
B14
C14
D14
E22
F22

如果你的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 13:25:47