[英]SQL query transposing columns
我有一個以下結構的表:
id | att1 | att2 | att3
-----------------------
1 | a1 | b1 | c1
2 | a2 | b2 | c2
3 | a3 | b3 | c3
我想將列轉置為每個id的行。 像這樣:
id | attname | value
------------------------
1 | att1 | a1
1 | att2 | b1
1 | att3 | c1
2 | att1 | a2
2 | att2 | b2
2 | att3 | c2
3 | att1 | a3
3 | att2 | b3
3 | att3 | c3
我正在閱讀PIVOT函數,不確定它是否能完成工作或如何使用它。 任何幫助,將不勝感激。
您可以將unpivot用於此任務。
SELECT *
FROM table
UNPIVOT (
value FOR att_name
IN (att1 as 'att1', att2 as 'att2', att3 as 'att3')
);
這是另一種方法:
SELECT id,attname, value
FROM Yourtable
CROSS APPLY ( VALUES ('att1',att1), ('att2',att2), ('att3',att3)) t(attname, value)
做UNION ALL
:
select id, 'att1' as attname, att1 as value from tablename
union all
select id, 'att2' as attname, att2 as value from tablename
union all
select id, 'att3' as attname, att3 as value from tablename
請注意, VALUE
是SQL中的保留字,因此,如果這是您的真實列名,則需要將其雙引號"value"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.