SQL Server : Columns to Rows

后端 未结 6 1276
孤城傲影
孤城傲影 2020-11-22 03:11

Looking for elegant (or any) solution to convert columns to rows.

Here is an example: I have a table with the following schema:

[ID] [EntityID] [Indi         


        
6条回答
  •  我寻月下人不归
    2020-11-22 03:35

    Just to help new readers, I've created an example to better understand @bluefeet's answer about UNPIVOT.

     SELECT id
            ,entityId
            ,indicatorname
            ,indicatorvalue
      FROM (VALUES
            (1, 1, 'Value of Indicator 1 for entity 1', 'Value of Indicator 2 for entity 1', 'Value of Indicator 3 for entity 1'),
            (2, 1, 'Value of Indicator 1 for entity 2', 'Value of Indicator 2 for entity 2', 'Value of Indicator 3 for entity 2'),
            (3, 1, 'Value of Indicator 1 for entity 3', 'Value of Indicator 2 for entity 3', 'Value of Indicator 3 for entity 3'),
            (4, 2, 'Value of Indicator 1 for entity 4', 'Value of Indicator 2 for entity 4', 'Value of Indicator 3 for entity 4')
           ) AS Category(ID, EntityId, Indicator1, Indicator2, Indicator3)
    UNPIVOT
    (
        indicatorvalue
        FOR indicatorname IN (Indicator1, Indicator2, Indicator3)
    ) UNPIV;
    

提交回复
热议问题