我正在嘗試提出一個選擇陳述句,該陳述句將采用多列并將它們放入一列中例如,如果我有如下資料:
id d1 d2
1 R04.0
1 Z00.129 Z13.220
2 Z00.129 Z68.36
2 Z23
3 Z23
我希望資料看起來像這樣
id column 1
1 R04.0
1 Z00.129
1 Z13.220
2 Z00.129
2 Z23
2 Z68.36
3 Z23
我嘗試查看資料透視表,但我認為這不是我要尋找的。我可能會寫一個游標,但這似乎非常低效。
uj5u.com熱心網友回復:
因為其他答案要么不完整,要么過于復雜,這里有另一種選擇。
注意我假設它d1永遠不會為空/空,但d2可能是這樣,并且您希望您的結果按id和col1
select id, d1 col1
from MyTable
union all
select id, d2 col1
from MyTable
where d2 is not null
order by id, col1;
uj5u.com熱心網友回復:
AUNION ALL應該可以解決問題。
SELECT id, column1 = d1 FROM data WHERE d1 IS NOT NULL
UNION ALL
SELECT id, column1 = d2 FROM data WHERE d2 IS NOT NULL
ORDER BY id, column1
uj5u.com熱心網友回復:
無需實際使用動態 SQL 即可動態 UNPIVOT 資料的另一種選擇
注意我們只需要排除列/鍵 ID
示例或dbFiddle
Select A.id
,Column1 = B.Value
From YourTable A
Cross Apply OpenJSON( (Select A.* For JSON Path,Without_Array_Wrapper ) ) B
Where [Key] not in ('id')
結果
id Column1
1 R04.0
1 Z00.129
1 Z13.220
2 Z00.129
2 Z68.36
2 Z23
3 Z23
編輯 - 如果您還想查看列名
Select A.id
,ColName = B.[key]
,ColValue = B.Value
From YourTable A
Cross Apply OpenJSON( (Select A.* For JSON Path,Without_Array_Wrapper ) ) B
Where [Key] not in ('id')
結果
id ColName ColValue
1 d1 R04.0
1 d1 Z00.129
1 d2 Z13.220
2 d1 Z00.129
2 d2 Z68.36
2 d1 Z23
3 d1 Z23
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/340097.html
標籤:sql sql-server 查询语句
