2016-12-21 57 views
1

我在嘗試實現MSSQL中的某些數據時遇到了一些困難。在這裏我有什麼:需要幫助PIVOT/UNPIVOT SQL中的一些數據

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  | 

我真的很感激,如果你能給我一些幫助或建議(包括更改第一個表)。

回答

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 
+0

您的代碼解決我的問題,現在,謝謝。 – Acunk

0

您可以使用一個簡單的SELECT與UNION ALL如下

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 
+0

你的答案是有效的,像@Ranjana的,不同的只在第6行,我應該把它改爲NULL/0。不管怎麼說,還是要謝謝你 – Acunk