SQL Server : Columns to Rows

后端 未结 6 1281
孤城傲影
孤城傲影 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:47

    Just because I did not see it mentioned.

    If 2016+, here is yet another option to dynamically unpivot data without actually using Dynamic SQL.

    Example

    Declare @YourTable Table ([ID] varchar(50),[Col1] varchar(50),[Col2] varchar(50))
    Insert Into @YourTable Values 
     (1,'A','B')
    ,(2,'R','C')
    ,(3,'X','D')
    
    Select A.[ID]
          ,Item  = B.[Key]
          ,Value = B.[Value]
     From  @YourTable A
     Cross Apply ( Select * 
                    From  OpenJson((Select A.* For JSON Path,Without_Array_Wrapper )) 
                    Where [Key] not in ('ID','Other','Columns','ToExclude')
                 ) B
    

    Returns

    ID  Item    Value
    1   Col1    A
    1   Col2    B
    2   Col1    R
    2   Col2    C
    3   Col1    X
    3   Col2    D
    

提交回复
热议问题