SQL - Pivot table and group by not working

前端 未结 2 1210
死守一世寂寞
死守一世寂寞 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:36

    You can't GROUP BY activity, document, extraction within the PIVOT table operator, the PIVOT operator infers the grouped columns automatically. But you can write it this way:

    WITH Pivoted
    AS
    (
      SELECT *
      FROM table1
      PIVOT 
      ( 
        sum([Count]) FOR [Type] IN ( Document , 
                                    Extraction)
      ) AS p
    ) 
    SELECT 
      product,
      SUM(Users) AS TotalUsers,
      MAX(DAte) AS LatestDate,
      MAX(Document) AS Document,
      MAX(Extraction) AS Extraction
    FROM Pivoted
    GROUP BY Product;
    

    SQL Fiddle Demo

    This will give you:

    | PRODUCT | TOTALUSERS |                   LATESTDATE | DOCUMENT | EXTRACTION |
    -------------------------------------------------------------------------------
    |   prodA |         60 | March, 02 2013 02:00:00+0000 |      113 |        152 |
    |   prodB |         45 | March, 02 2013 02:00:00+0000 |       40 |         73 |
    

    Update 1

    WITH a
    AS(
      SELECT    
        activity, 
        username, 
        [Last Accessed] = max(DATEADD(dd, 
                                      DATEDIFF(d, 0, ActDateTime), 
                                      0)), 
        --[#Users] = count(distinct username), 
        CASE 
          WHEN COUNT(activity) IS NOT NULL THEN 1 
          ELSE 0 
        END AS Count,
        CASE 
          WHEN pageURL LIKE '/Document%'
            OR pageURL LIKE '/Database%' THEN 'Document'
          ELSE 'Extraction' 
        END AS [Type] 
      from activitylog
      where pageURL not like '%home%' 
        AND pageURL not like '/Default%'
      group by activity, 
               username, 
               ...
    ), Pivoted
    AS
    (
      SELECT *
      FROM a
      PIVOT 
      ( 
        sum([Count]) FOR [Type] IN ( Document , 
                                     Extraction)
       ) AS p
    ) 
    SELECT 
      product,
      SUM(Users) AS TotalUsers,
      MAX(DAte) AS LatestDate,
      MAX(Document) AS Document,
      MAX(Extraction) AS Extraction
    FROM Pivoted
    GROUP BY Product; 
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题