SQL Server pivot using case statement

前端 未结 2 1711
悲哀的现实
悲哀的现实 2020-12-21 16:03

I\'m trying to pivot out some data and I think I need to incorporate a case statement in my pivot code but I\'m not sure how. I have the table below:

ID              


        
相关标签:
2条回答
  • 2020-12-21 16:22

    You need to use aggregate on top of case statements

    SELECT id,
           Max(CASE
                 WHEN LEFT(areaID, 1) = 1 THEN 'Yes'
               END) Head,
           Max(CASE
                 WHEN LEFT(areaID, 1) = 2 THEN 'Yes'
               END) Face,
           Max(CASE
                 WHEN LEFT(areaID, 1) = 3 THEN 'Yes'
               END) Neck,
           Max(CASE
                 WHEN LEFT(areaID, 1) = 4 THEN 'Yes'
               END) Abdo
    FROM   #testcase
    GROUP  BY id 
    
    0 讨论(0)
  • 2020-12-21 16:35

    You could use a real PIVOT solution instead like this:

    DECLARE @t table(ID int, AreaCode int)
    INSERT @t 
    VALUES
      (1001,1501),(1001,1502),(1001,2301),(1031,1010),
      (1031,3012),(1048,2304),(1048,3012),(1048,4022)
    
    SELECT id, [1]Head, [2]Face, [3]Neck, [4]Abdo
    FROM  
    ( 
      SELECT id, left(AreaCode, 1) Area, 'Yes' x
      FROM @t
    ) p 
    PIVOT (Max(x) FOR [Area] IN ([1],[2],[3],[4])) AS pvt 
    

    Result:

    id    Head  Face  Neck  Abdo
    1001  Yes   Yes   NULL  NULL
    1031  Yes   NULL  Yes   NULL
    1048  NULL  Yes   Yes   Yes
    
    0 讨论(0)
提交回复
热议问题