SQL: 将多列转换为行
SQL: Convert multiple columns to rows
我有一个 table 格式如下
我需要将其转换为这种格式
所以基本上我希望将多列转换为行。有人可以帮我弄这个吗?
谢谢
尝试
select *
from yourTable
unpivot (
Value
for NewCol in (Value1, Value2, Value3,Value4, Value5)
) up
将列转换为行称为逆透视。将行转换为列是旋转的。
逆透视数据的一种方法是合并 apply operator with a table value constructor。
此示例使用 common table expression (CTE) 到 return 3 个样本记录。
Id ColumnOne ColumnTwo ColumnThree
1 a b c
2 d e f
3 g h i
例子
-- Unpivoting with apply and VALUES.
WITH SampleData AS
(
/* This CTE returns 3 sample records.
*/
SELECT
cte.*
FROM
(
VALUES
(1, 'a', 'b', 'c'),
(2, 'd', 'e', 'f'),
(3, 'g', 'h', 'i')
) AS cte(Id, ColumnOne, ColumnTwo, ColumnThree)
)
SELECT
sd.Id,
ca.*
FROM
SampleData AS sd
CROSS APPLY
(
VALUES
(ColumnOne),
(ColumnTwo),
(ColumnThree)
) AS ca (ColumnFour)
;
returned 输出如下所示:
Id ColumnFour
1 a
1 b
1 c
2 d
2 e
2 f
3 g
3 h
3 i
我个人更喜欢@nazark 的方法。使用 UNPIVOT operator helps others to follow the intention of your code. If that answer helped you please accept it。接受答案会奖励贡献者 his/her 的努力,并帮助遇到相同问题的其他人找到可行的答案。
我有一个 table 格式如下
所以基本上我希望将多列转换为行。有人可以帮我弄这个吗?
谢谢
尝试
select *
from yourTable
unpivot (
Value
for NewCol in (Value1, Value2, Value3,Value4, Value5)
) up
将列转换为行称为逆透视。将行转换为列是旋转的。
逆透视数据的一种方法是合并 apply operator with a table value constructor。
此示例使用 common table expression (CTE) 到 return 3 个样本记录。
Id ColumnOne ColumnTwo ColumnThree
1 a b c
2 d e f
3 g h i
例子
-- Unpivoting with apply and VALUES.
WITH SampleData AS
(
/* This CTE returns 3 sample records.
*/
SELECT
cte.*
FROM
(
VALUES
(1, 'a', 'b', 'c'),
(2, 'd', 'e', 'f'),
(3, 'g', 'h', 'i')
) AS cte(Id, ColumnOne, ColumnTwo, ColumnThree)
)
SELECT
sd.Id,
ca.*
FROM
SampleData AS sd
CROSS APPLY
(
VALUES
(ColumnOne),
(ColumnTwo),
(ColumnThree)
) AS ca (ColumnFour)
;
returned 输出如下所示:
Id ColumnFour
1 a
1 b
1 c
2 d
2 e
2 f
3 g
3 h
3 i
我个人更喜欢@nazark 的方法。使用 UNPIVOT operator helps others to follow the intention of your code. If that answer helped you please accept it。接受答案会奖励贡献者 his/her 的努力,并帮助遇到相同问题的其他人找到可行的答案。