Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pivot or unpivot

I have a table with hourly statistics that I need to pivot (or unpivot?)

The starting table is of the form:

[SystemID] [Hour] [CallStarts] [AvgDuration]  
    1         0        3           27
    1         1       10           58
    1         2       43           45
    1         3       54           63
    2         0        6           56
    2         1       46           98
    2         2       56           67
    2         3       65           77  

And I need the output to be:

[SystemID] [Statistic] [Hr0] [Hr1] [Hr2] [Hr3]  
     1     CallStarts    3    10     43    54  
     1     AvgDuration  27    58     45    63
     2     CallStarts    6    46     56    65
     2     AvgDuration  56    98     67    77  

I'm using SQL Server 2008R2. I understand the basics of pivot tables but I don't have much experience with them. Its the [Statistic] column that has me for a loss.

like image 452
Dino Avatar asked Mar 15 '26 17:03

Dino


1 Answers

Here is a way to get these results without pivot, depending on indexes and data size it may be faster:

SELECT SystemID, 
       MAX('CallStarts') AS Statistic, 
       SUM(CASE WHEN Hour = 0 THEN CallStarts ELSE 0 END) AS Hr0,
       SUM(CASE WHEN Hour = 1 THEN CallStarts ELSE 0 END) AS Hr1,
       SUM(CASE WHEN Hour = 2 THEN CallStarts ELSE 0 END) AS Hr2,
       SUM(CASE WHEN Hour = 3 THEN CallStarts ELSE 0 END) AS Hr3
FROM Table
GROUP BY SystemID
  UNION ALL
SELECT SystemID, 
       MAX('AvgDuration') AS Statistic, 
       SUM(CASE WHEN Hour = 0 THEN AvgDuration ELSE 0 END) AS Hr0,
       SUM(CASE WHEN Hour = 1 THEN AvgDuration ELSE 0 END) AS Hr1,
       SUM(CASE WHEN Hour = 2 THEN AvgDuration ELSE 0 END) AS Hr2,
       SUM(CASE WHEN Hour = 3 THEN AvgDuration ELSE 0 END) AS Hr3
FROM Table
GROUP BY SystemID
ORDER BY SystemID, Statistic ASC
like image 153
Hogan Avatar answered Mar 21 '26 22:03

Hogan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!