[英]How to transfer data from wide format to long format in Excel Or SQL?
我有如下所示的数据。任何想法如何在Excel或SQL中从宽格式转换为长格式。
ID TOTAL SCORE PLAYER
34543 12342 456 45
45632 34521 241 33
输出:
ID DATA_TYPE VALUE
34543 TOTAL 12342
34543 SCORE 34521
34543 PLAYER 45
45632 TOTAL 34521
45632 SCORE 241
45632 PLAYER 33
我首选的取消透视的方法是使用apply
:
select t.id, v.*
from t cross apply
(values ('TOTAL', total), ('SCORE', score), ('PLAYER', player)
) v(DATA_TYPE, VALUE);
除了简洁之外,这是对横向连接的一个很好的介绍。 这是SQL中非常强大的构造,可用于许多其他目的(与UNPIVOT
不同)。 它还只扫描表一次,因此它比UNION ALL
效率更高。
您需要在查询中使用UNPIVOT
。 尝试这个:
--sample data
declare @t table (id int, total int, score int, player int)
insert into @t values
(34543, 12342, 456, 45),
(45632, 34521, 241, 33)
--query that will return deisred result
select Id, Data_Type, Value from (
select * from @t
) [t] unpivot (
VALUE for DATA_TYPE in (total, score, player)
) [u]
使用此查询:
SELECT *
FROM
(SELECT distinct ID, 'TOTAL' AS DATA_TYPE, TOTAL AS VALUE
FROM Your_Table
UNION
SELECT distinct ID, 'SCORE' AS DATA_TYPE, SCORE AS VALUE
FROM Your_Table
UNION
SELECT distinct ID, 'PLAYER' AS DATA_TYPE, PLAYER AS VALUE
FROM Your_Table) as tbl
ORDER BY ID
如果您的Excel版本是2010或更高版本,则可以使用Power Query(在Excel 2016中又称为Get&Transform)并取消除ID列之外的所有内容。
从GUI轻松完成
要么
码
let
Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"ID", Int64.Type}, {"TOTAL", Int64.Type}, {"SCORE", Int64.Type}, {"PLAYER", Int64.Type}}),
#"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Changed Type", {"ID"}, "Attribute", "Value")
in
#"Unpivoted Other Columns"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.