我想从多列中创建一列。我在MSSQL中努力做到这一点。
ID | Type1 | Type2
0 | Yellow | Blue
1 | Blue | Yellow
我希望:
ID | TYPE_ALL | TYPE
0 | Yellow | Type1
0 | Blue | Type2
1 | Blue | Type1
1 | Yellow | Type2
拜托,你知道怎么做吗?
谢谢。
答案 0 :(得分:5)
这里可以使用UNPIVOT:
SELECT *
FROM Table
UNPIVOT
(Type_ALL FOR TYPE IN
(Type1, Type2)
)AS unpvt;
答案 1 :(得分:3)
SELECT ID, Type1 AS TYPE_ALL, 'Type1' AS [TYPE] FROM YourTable
UNION ALL
SELECT ID, Type2 AS TYPE_ALL, 'Type2' AS [TYPE] FROM YourTable
答案 2 :(得分:3)
如果您不想UNPIVOT
,则可以使用UNION
查询:
SELECT ID,
Type1 AS TYPE_ALL,
'Type1' AS TYPE
FROM yourTable
UNION ALL
SELECT ID,
Type2,
'Type2'
FROM yourTable
ORDER BY ID