简体   繁体   中英

Aggregate function within inner select in Pivot query using SQL Server

I have the following table:

select * from product;

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

Now I need to do pivoting for this table for which i am using following query:

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)

Result:

 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

Note The total of product RAM is 3 but in Column RAM showing only 1. I have used COUNT(*) aggregate function within the inner select statement in @query . How can i show actual count?

You only need to group by slno , not by the combination of slno and item . Therefore, you need to change the query which provides a source for your pivot as follows:

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

Use following sub query instead of your sub query:

select slno,Count(*) OVER (PARTITION BY slno) as TotalProduct,item
from product

Edit: Count(*) Over(Partition by ...) supported in SQL Server 2012 and above versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM