使用SQL Server在数据透视查询中的内部选择内的聚合函数

时间:2014-08-25 06:33:32

标签: sql sql-server pivot-table

我有下表:

select * from product;

slno  item
---------------
1     HDD
2     PenDrive
3     RAM
4     DVD
5     RAM
6     HDD
7     RAM
7     RAM
7     RAM

现在我需要为我正在使用以下查询的表格进行透视:

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(item) 
                from product
                group by item
                  order by item
        FOR XML PATH(''), TYPE
        ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,'')



set @query = 'SELECT slno,TotalProduct ,' + @cols + ' 
        from 
        (
            select slno,Count(*) as TotalProduct,item
            from product
            group by slno,item
        ) x
        pivot 
        (
            count(item)
            for item in (' + @cols + ')
        ) p '

exec(@query)

结果:

 slno  TotalProducts  DVD  HDD  PenDrive  RAM
 ---------------------------------------------
 1         1           0    1      0       0
 2         1           0    0      1       0
 3         1           0    0      0       1
 4         1           1    0      0       0
 5         1           0    0      0       1
 6         1           0    1      0       0
 7         3           0    0      0       1

注意产品RAM的总数为3,但在列RAM中仅显示1.我在COUNT(*)的内部select语句中使用了@query聚合函数。我怎样才能显示实际数量?

2 个答案:

答案 0 :(得分:1)

您只需按slno分组,而不是slnoitem的组合。因此,您需要更改为您的数据透视提供源的查询,如下所示:

set @query = 'SELECT slno,totalproduct,' + @cols + ' 
    from 
    (
        select p.slno slno, c.count as totalproduct, p.item
        from product p
        inner join 
        (select slno, count(item) count
         from product 
         group by slno) c on p.slno = c.slno
    ) x
    pivot 
    (
        count(item)
        for item in (' + @cols + ')
    ) p '

Demo

答案 1 :(得分:1)

使用以下子查询代替您的子查询:

select slno,Count(*) OVER (PARTITION BY slno) as TotalProduct,item
from product
SQL Server 2012及更高版本支持

编辑: Count(*) Over(Partition by ...)