0

Table: Sample

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

Expected Result:

 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   

I want to get the MS and Status value for each day from 1 to 31 for each ID.

I have used PIVOT to get the below result.

Result:

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

 2    NULL  NULL  3        5      6   

Query:

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

How can I merge the Status column with the result?.

2
  • simply consider the result you got as one table 't1' and create same with the second option i.e. with Status 't2' and join it with id Nov 27, 2014 at 5:48
  • I have tried what you said. But is there any possibility to do it with the single PIVOT. Nov 27, 2014 at 5:53

1 Answer 1

2

Try this. Use Another Pivot to transpose Status column. Then use aggregate (Max or Min) in select column list with group by Id to get the Result.

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.