sql >> Database teknologi >  >> RDS >> Sqlserver

SQL - Pivot tabel og gruppe ved ikke at virke

Du kan ikke GROUP BY activity, document, extraction i PIVOT tabeloperatoren, PIVOT operatør udleder de grupperede kolonner automatisk. Men du kan skrive det på denne måde:

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

Dette vil give dig:

| 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 |

Opdatering 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; 
 


  1. Kører sql-scripts med indbyrdes afhængigheder

  2. bruger c# datetime i mysql opdateringsforespørgsel

  3. PHP - bruger STR_TO_DATE opdatering dato og klokkeslæt kolonne, men den er opdateret tom post som 0000-00-00 00:00:00

  4. Den bedste måde at fjerne værdi fra SET-feltet?