透视多列

时间:2014-12-31 01:19:31

标签: sql sql-server sql-server-2008 pivot

我有以下计算数据

Pl_Name      Cnt       Status       Level

CF            21       Active         2

CF            3        Closed         2

INFRA         1        Closed         3

OTHER         40       Active         2

OTHER         4        Active         3

OTHER         2        Closed         1

OTHER         9        Closed         2

OTHER         5        Closed         3

MSG           5        Active         2

用于上述结果的查询是

SELECT Platforms.PlatformName,COUNT(Ticket.TicketId) AS Count,Ticket.TicketStatus,Ticket.Priority
FROM Platforms
INNER JOIN Ticket
ON Platforms.ID = Ticket.Platform_id
GROUP BY Platforms.PlatformName,Ticket.TicketStatus,Ticket.Priority

现在我需要上面结果的以下结果

              Level1              Level2             Level3

PL_Name  Active    Closed    Active    Closed    Active    Closed

CF         0         0         21        3         0         0

INFRA      0         0         0         0         0         1

OTHER      0         2         40        5         4         5

MSG        0         0         2         0         0         0

1 个答案:

答案 0 :(得分:0)

试试这个..您需要使用pivot将行转置为列。

SELECT Pl_Name,
       Isnull([Level1_active], 0)[Level1_active],
       Isnull([Level1_closed], 0)[Level1_closed],
       Isnull([Level2_active], 0)[Level2_active],
       Isnull([Level2_closed], 0)[Level2_closed],
       Isnull([Level3_active], 0)[Level3_active],
       Isnull([Level3_closed], 0)[Level3_closed]
FROM  (SELECT Pl_Name,
              cnt,
              'Level' + CONVERT(VARCHAR(50), level) + '_'
              + status piv_col
       FROM   Computeddata) a
      PIVOT (Max(cnt)
            FOR piv_col IN([Level1_active],
                           [Level1_closed],
                           [Level2_active],
                           [Level2_closed],
                           [Level3_active],
                           [Level3_closed])) piv 

注意:结果是与您的结果列标题类似的结果可能与预期相同