0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

Have you checked your script before posting?
Count(*) Over (Partition by) supported in SQL Server 2012 and above version.
the result of my query completely like result of shree.pat sub query.
Oh! "Apologize" I am using 2008. Plz edit your answer so that I can up vote it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.