首页 > 解决方案 > SQL 显示每行重复记录的总数

问题描述

我想添加一列,显示“名称”在其他行中出现的次数。基本上是该名称出现的总次数,但列在每一行。

select number, name from table;

添加前的样本数据:

number  name     
1234    storeA
1235    storeA
1236    storeA
1237    storeB
1238    storeC
1239    storeC

添加后所需的输出

number  name    Total
1234    storeA  3
1235    storeA  3
1236    storeA  3
1237    storeB  1
1238    storeC  2
1239    storeC  2

标签: sqlsql-server

解决方案


您可以使用窗口功能:

select t.*,
       count(*) over (partition by name) as total
from table t;

但是,ANSI如果窗口函数不起作用,SQL 标准会提供关联子查询方法:

select t.*,
       (select count(*)
        from table t1
        where t1.name = t.name
       ) as total
from table t;

推荐阅读