如何在Excel或SQL中将数据从宽格式传输到长格式?

时间:2018-05-07 07:46:19

标签: sql sql-server excel sql-server-2008 tsql

我有如下所示的数据。任何想法如何在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

4 个答案:

答案 0 :(得分:5)

我首选的解除隐私方法是使用apply

select t.id, v.*
from t cross apply
     (values ('TOTAL', total), ('SCORE', score), ('PLAYER', player)
     ) v(DATA_TYPE, VALUE);

除了相当简洁之外,这是对横向连接的一个很好的介绍。这是SQL中非常强大的构造,可用于许多其他目的(与UNPIVOT不同)。它也只扫描一次表,因此它比UNION ALL更有效。

答案 1 :(得分:2)

您需要在查询中使用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]

答案 2 :(得分:1)

使用此查询:

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

答案 3 :(得分:1)

如果您的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"