简体   繁体   中英

Transpose columns to rows using SQL query, maybe using pivot?

Input :

Empl ID Name January-16 February-16 March-16    Activity 
----------------------------------------------------------
1234    Test1   30         10         1         Running 
1234    Test1   0           0         8         Sleeping
4567    Test2   20         20         2         Reading 
4567    Test2   0          30         20        Reading 
2345    Test3   10         10         3         Sleeping
2345    Test3   0           0         9         Running 

into :

Empl ID Name    Date        Costs   Activity 
--------------------------------------------------
1234    Test1   January-16   30     Running 
1234    Test1   February-16  10     Running 
1234    Test1   March-16     1      Running 
1234    Test1   March-16     8      Sleeping
SELECT *
FROM
    #Table
    UNPIVOT (
       Costs FOR C IN ([January-16], [February-16], [March-16])
    ) up
WHERE
    Costs <> 0    

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM