SQL - Pivot table and group by not working

前端 未结 2 1209
死守一世寂寞
死守一世寂寞 2020-12-16 22:19

I have a table as follows:

Product     #users  Date            Count   Type
prodA       29      2013-02-27      113     Document
prodA       31      2013-03-         


        
2条回答
  •  被撕碎了的回忆
    2020-12-16 22:55

    You can achieve it using CTE.

    ;WITH CTE  
    AS  
    (  
        SELECT *   
        FROM Sample  
        PIVOT  
           (SUM([COUNT]) FOR [TYPE] IN (Document, Extraction)) AS PI  
    )  
    
    SELECT   
         Product,  
         SUM(Users) AS Users,  
         MAX(Date) AS Date,  
         MAX(Document) AS Document,  
         MAX(Extraction) AS Extraction  
    FROM CTE  
    GROUP BY Product;  
    

    SQL Fiddle Demo

提交回复
热议问题