【问题标题】:How to transfer data from wide format to long format in Excel Or SQL?如何在 Excel 或 SQL 中将数据从宽格式传输到长格式?
【发布时间】:2018-05-07 07:46:19
【问题描述】:

我有一个如下所示的数据。知道如何在 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

【问题讨论】:

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


    【解决方案1】:

    我首选的反透视方法是使用apply

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

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

    【讨论】:

    • 由于OP没有提到SQL的哪个版本,我认为这只适用于2012年或以后?
    【解决方案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]
    

    【讨论】:

      【解决方案3】:

      使用这个查询:

      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
      

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-01-26
          • 2022-01-25
          • 2021-05-12
          • 2022-01-11
          相关资源
          最近更新 更多