需要帮助PIVOT / UNPIVOT SQL中的一些数据

时间:2016-12-21 05:38:25

标签: sql-server pivot unpivot

我在尝试在MSSQL中实现某些数据时遇到了一些困难。我在这里:

SO_ID | SO_DATE | WAGE_A | WAGE_B | WAGE_B_DUR | 
1     | 12/12/06| 100    |   200  |    15      | 
2     | 10/10/06| 150    |   250  |    10      |

我想要的是什么:

SO_ID | SO_DATE | WAGE_TYPE | AMOUNT | DURATION |
1     | 12/12/06| WAGE_A    | 100    | NULL     |
1     | 12/12/06| WAGE_B    | 200    | 15       |
2     | 10/10/06| WAGE_B    | 250    | 10       |
2     | 10/10/06| WAGE_A    | 150    | NULL     |

如果你能给我一些帮助或建议(包括改变第一张表),我真的很感激。

2 个答案:

答案 0 :(得分:1)

尝试:

CREATE TABLE try_val(SO_ID int, SO_DATE int, WAGE_A int, WAGE_B int, WAGE_B_DUR int) 

insert into try_val values (1     , 12/12/06, 100    ,   200  ,    15      ) 
insert into try_val values (2     , 10/10/06, 150    ,   250  ,    10      )


select SO_ID,SO_DATE,'WAGE_A' AS WAGE_TYPE,WAGE_A AS AMOUNT,NULL AS DURATION from try_val 
UNION ALL
select SO_ID,SO_DATE,'WAGE_B' AS WAGE_TYPE,WAGE_A AS AMOUNT,WAGE_B_DUR  AS DURATION from try_val
ORDER BY SO_ID

答案 1 :(得分:0)

您可以使用UNION ALL的简单SELECT,如下所示

select
    SO_ID,
    SO_DATE,
    WAGE_TYPE = 'WAGE_A',
    AMOUNT = WAGE_A,
    DURATION = WAGE_B_DUR
from myData
union all
select
    SO_ID,
    SO_DATE,
    WAGE_TYPE = 'WAGE_B',
    AMOUNT = WAGE_B,
    DURATION = WAGE_B_DUR
from myData
order by SO_ID