需要计数没有临时表的行组

时间:2018-04-09 13:56:27

标签: sql sql-server

我正在使用不允许使用临时表的专有SQL系统。我试图计算一个成员对所包含细节的索赔数量:

    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;

如果没有临时表,如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

只需使用count(*)的窗口函数:

select claim, name, count(*) over (partition by claim, name)
from @t t;