Mattl
Mattl

Reputation: 1618

Simple data pivot

I have a query (select [type], a, b, c, d, e from MyTable) that returns:

[type], [a], [b], [c], [d], [e]
type 1,  x ,  x ,  x ,  x ,  x
type 2,  x ,  x ,  x ,  x ,  x
type 3,  x ,  x ,  x ,  x ,  x

I'd like to pivot the data so it displays as:

[]     , [type 1], [type 2], [type 3] 
[a]    , x       , x       , x
[b]    , x       , x       , x
[c]    , x       , x       , x
[d]    , x       , x       , x 
[e]    , x       , x       , x   

Any pointers on the SQL here would be appreciated.

Upvotes: 3

Views: 106

Answers (2)

Oleg Grishko
Oleg Grishko

Reputation: 4281

What we need is:

SELECT  Col, [type 1], [type 2], [type 3]
FROM    (SELECT [type], Amount, Col
         FROM   (SELECT [type], [a], [b], [c], [d], [e]
                FROM    _MyTable) as sq_source
                UNPIVOT (Amount FOR Col IN ([a], [b], [c], [d], [e])) as sq_up) as sq 
PIVOT (MIN(Amount) FOR [type] IN ([type 1], [type 2], [type 3])) as p;

But since the types number is undetermined, we have to do it dynamically

DECLARE @cols NVARCHAR(2000)
SELECT  @cols = COALESCE(@cols + ',[' + [type] + ']',
                         '[' + [type] + ']')
FROM    _MyTable
ORDER BY [type]

DECLARE @query NVARCHAR(4000)
SET @query = N'SELECT   Col, ' + @cols + '
FROM    (SELECT [type], Amount, Col
         FROM   (SELECT [type], [a], [b], [c], [d], [e]
                FROM    _MyTable) as sq_source
                UNPIVOT (Amount FOR Col IN ([a], [b], [c], [d], [e])) as sq_up) as sq 
PIVOT (MIN(Amount) FOR [type] IN (' + @cols + ')) as p;';

EXECUTE(@query)

But be careful, because this query is technically a vector for an injection.

Upvotes: 1

Michal Barcik
Michal Barcik

Reputation: 662

Something like this?

create table #test
(
type varchar(10),
a varchar(10),
b varchar(10),
c varchar(10),
d varchar(10),
e varchar(10)
)

insert into #test values
('type 1',  'x' ,  'x' ,  'x' ,  'x'  , 'x'),
('type 2',  'x' ,  'x' ,  'x' ,  'x' ,  'x'),
('type 3',  'x' ,  'x' ,  'x' ,  'x' ,  'x')

select * from
(

   select * from
   (
      select * from #test
   )data_to_unpivot
   UNPIVOT
   (
   Orders FOR [xxx] IN (a,b,c,d,e)

   )UNPIVOTED_DATA 
)data_to_pivot
PIVOT
(
MAX(orders) for type in ([type 1],[type 2],[type 3])
)PIVOTED_DATA   

Upvotes: 1

Related Questions