2

I'm having a hard time wrapping my head around pivot/unpivot - all examples I find online I think are more complex than I need.

Imagine a table as such:

CREATE TABLE Custom (ID tinyint identity, value nvarchar(20))
INSERT INTO Custom VALUES ('red')
INSERT INTO Custom VALUES ('green')
INSERT INTO Custom VALUES ('blue')

The table displays like

ID    VALUE
1     red
2     green
3     blue

I want the table to display like

COLOR1    COLOR2    COLOR3
red       green     blue

Is this possible with UNPIVOT?

Thanks!

gemArt
  • 35
  • 6

2 Answers2

1

Here is one way to generate the desired results with conditional aggregation:

select 
    max(case when id = 1 then value end) color1,
    max(case when id = 2 then value end) color2,
    max(case when id = 3 then value end) color3
from custom

If you don't have a sequencial id starting at 1, you can emulate it with row_number():

select
    max(case when rn = 1 then value end) color1,
    max(case when rn = 2 then value end) color2,
    max(case when rn = 3 then value end) color3
from (select value, row_number() over(order by id) rn from mytable)
GMB
  • 216,147
  • 25
  • 84
  • 135
0

That isn't possible with UNPIVOT you'll want to use PIVOT. Microsoft documentation on the subject "Using PIVOT and UNPIVOT"

But here's an example using your test data with comments:

DECLARE @Custom TABLE
    (
        [ID] TINYINT IDENTITY
      , [value] NVARCHAR(20)
    );
INSERT INTO @Custom
VALUES ( 'red' )
     , ( 'green' )
     , ( 'blue' );

SELECT *
FROM   @Custom
    PIVOT (
              MAX([value])  --column being aggregated, the column values you want horizontal
              FOR [ID] IN ( [1], [2], [3] ) --The column that contains the value that will become the column headers.
          ) AS [pvt];

Giving use the results of

1                    2                    3
-------------------- -------------------- --------------------
red                  green                blue

Since you want the verbiage of 'COLOR' in the column headers we'll concat that in a sub-query with the ID column and tweak the pivot

SELECT *
FROM   (
           --Since you want 'COLOR' as part of the column name we do a sub-query and concat that verbiage with the ID
           SELECT CONCAT('COLOR', [ID]) AS [ColumnColor]
                , [value]
           FROM   @Custom
       ) AS [Cst]
PIVOT (
          MAX([value])  --Same as before, column being aggregated, the column values you want horizontal
          FOR [ColumnColor] IN ( [COLOR1], [COLOR2], [COLOR3] ) --This changes now to reflect the concatenated column and the new column header values
      ) AS [pvt];

Giving us the results of

COLOR1               COLOR2               COLOR3
-------------------- -------------------- --------------------
red                  green                blue
Tim Mylott
  • 2,553
  • 1
  • 5
  • 11