SQL Server - PIVOT - two columns into rows

后端 未结 2 705
你的背包
你的背包 2021-02-15 16:40

I saw many questions about PIVOT for a single column, each question more complex than other, however, I could not find anything like what I need.

To be honest, I don\'t

2条回答
  •  借酒劲吻你
    2021-02-15 17:09

    Try something like this

    CREATE TABLE #Table1
        ([uid] int, [name] varchar(4), [diseaseid] int, [intensity] varchar(4))
    ;
    
    INSERT INTO #Table1
        ([uid], [name], [diseaseid], [intensity])
    VALUES    (1, 'xxxx', 2, 'low')
        (1, 'xxxx', 1, 'high'),
    
    ;
    
    SELECT MAX([uid]) AS [uid]
           ,MAX([name]) AS [name]
           ,MAX([diseaseid1]) AS [diseaseid1]
           ,MAX([intensity1]) AS [intensity1]
           ,MAX([diseaseid2]) AS [diseaseid2]
           ,MAX([intensity2]) [intensity2]
    FROM 
    (
        SELECT [uid], [name]
        , CASE WHEN rn=2 THEN NULL ELSE [diseaseid] END AS [diseaseid1]
        , CASE WHEN rn=2 THEN NULL ELSE [intensity] END AS [intensity1]
        , CASE WHEN rn=1 THEN NULL ELSE [diseaseid] END AS [diseaseid2]
        , CASE WHEN rn=1 THEN NULL ELSE [intensity] END AS [intensity2]
        FROM
        (
            SELECT [uid], [name], [diseaseid], [intensity], 
            ROW_NUMBER() OVER(PARTITION BY [uid] ORDER BY Name) AS rn
            FROM #Table1
        ) T
    ) T
    GROUP BY [uid], [name]
    

提交回复
热议问题