我正在使用不允许使用临时表的专有 SQL 系统。我正在尝试计算一个成员(member)有多少 claim ,并包含详细信息:
declare @t table(claim int, name varchar(50))
insert into @t values(1, 'Anderson'),
(1, 'Anderson'),
(2, 'Anderson'),
(2, 'Anderson'),
(3, 'Anderson'),
(3, 'Anderson'),
(3, 'Anderson'),
(3, 'Anderson'),
(3, 'Anderson'),
(3, 'Anderson');
我想要的结果是:
Name Claim Count
Anderson 1 2
Anderson 1 2
Anderson 2 2
Anderson 2 2
Anderson 3 6
Anderson 3 6
Anderson 3 6
Anderson 3 6
Anderson 3 6
Anderson 3 6
我可以在 SQL Server 中使用临时表解决这个问题:
select claim, name, count(name) as count
into #counts
from @t
group by claim, name;
select *
into #detail
from @t;
select b.claim, b.name, a.count
from #counts a
inner join #detail b
on a.claim = b.claim
and a.name = b.name;
但是,正如我之前提到的,这必须在不允许使用临时表的专有 SQL 系统中运行。我尝试过使用 CTE,但无法让它提供详细信息:
;with cte
as(
select claim, name, row_number()over(partition by claim, name order by claim) as rn
from @t
)
select name, claim, max(rn) as counts
from cte
group by name, claim;
如果没有临时表,如何解决这个问题?
最佳答案
只需使用 count(*)
的窗口函数即可:
select claim, name, count(*) over (partition by claim, name)
from @t t;
关于sql - 需要没有临时表的行组计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49734745/