PIVOT值从两列到多列

时间:2014-11-27 05:42:57

标签: sql sql-server select pivot

表:示例

ID      Day    Status   MS
----------------------------
 1       1       0      10
 1       2       0      20
 1       3       1      15 
 2       3       1      3
 2       30      0      5
 2       31      0      6

预期结果:

 ID  Day1  Day2  Day3....Day30  Day31   Status1  Status2  Status3...Status30  Status31
 ---------------------------------------------------------------------------------------
 1    10    20    15      NULL   NULL      0        0        1           NULL     NULL   

 2    NULL  NULL  3        5      6        NULL     NULL     1            0         0   

我希望每个ID的每一天的MS and Status值为1到31。

我使用PIVOT来获得以下结果。

结果:

ID  Day1  Day2  Day3....Day30  Day31
-------------------------------------
 1    10    20    15      NULL   NULL

 2    NULL  NULL  3        5      6   

查询:

SELECT 
     ID
    ,[1]     AS Day1
    ,[2]     AS Day2
    ,[3]     AS Day3
        .
        .
        .
    ,[30]    AS Day30
    ,[31]    AS Day31
FROM
(
    SELECT 
        ID
        ,[Day]
        ,MS
    FROM 
        Sample  
) AS A
PIVOT
(
    MIN(MS)
    FOR [Day] IN([1],[2],[3],...[30],[31]) 
) AS pvtTable

如何将Status列与结果合并?。

1 个答案:

答案 0 :(得分:2)

试试这个。使用另一个Pivot转置 Status列。然后在选择列列表中使用汇总(MaxMin),并按Id分组获取结果。

CREATE TABLE #est
  (ID INT,[Day] INT,[Status] INT,MS INT)

INSERT #est
VALUES (1,1,0,10),(1,2,0,20),(1,3,1,15 ),
       (2,3,1,3),(2,30,0,5),(2,31,0,6) 


SELECT ID,
       Max([Day1])    [Day1],
       Max([Day2])    [Day2],
       Max([Day3])    [Day3],
       Max([Day30])   [Day30],
       Max([Day31])   [Day31],
       Max([status1]) [status1],
       Max([status2]) [status2],
       Max([status3]) [status3],
       Max([status30])[status30],
       Max([status31])[status31]
FROM   (SELECT Id,
               'status' + CONVERT(VARCHAR(30), Day) col_stat,
               'Day' + CONVERT(VARCHAR(30), Day)    Col_Day,
               [status],
               ms
        FROM   #est) a
       PIVOT (Min([ms])
             FOR Col_Day IN([Day1],[Day2],[Day3],[Day30],[Day31])) piv 
       PIVOT (Min([status]) FOR col_stat IN ([status1],[status2],[status3],[status30],[status31])) piv1
GROUP BY id