PIVOT/UNPIVOT SQL 中的一些数据需要帮助
Need help to PIVOT/UNPIVOT some data in SQL
我在尝试在 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 |
如果您能给我一些帮助或建议(包括更改第一个table),我将不胜感激。
试试看:
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
您可以使用一个简单的 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
我在尝试在 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 |
如果您能给我一些帮助或建议(包括更改第一个table),我将不胜感激。
试试看:
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
您可以使用一个简单的 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