Unpivot

0

Please login or register to vote for this query.

(click on this box to dismiss)

Lifehacks

Q&A for people looking to bypass life's everyday problems with simple tricks

declare @T table
    (
      ID int,
      Column1 char(1), 
      Column2 char(1), 
      Column3 char(1),
      Column4 char(1),
      Column5 char(1)
    )
    
    insert into @T values
    (1,   'A',        'C',       'D',        'A',      'B'),
    (2,   'A',        'D',       'A',        'B',      'A'),
    (3,   'B',        'K',       'Q',        'C',      'Q'),
    (4,   'A',        'K',       'E',        'E',      'B'),
    (5,   'F',        'K',       'F',        'F',      'S')
    
    ;with C as
    (
      select ID, Col, Val
      from (
             select ID, Column1, Column2, Column3, Column4, Column5
             from @T
           ) as P
      unpivot (Val for Col in (Column1, Column2, Column3, Column4, Column5)) as U   
    )
    select Col, Val, count(*) as ValCount
    from C
    group by Col, Val
    order by Col

Enter Parameters

Options:
Switch to meta site
loading Hold tight while we fetch your results