简单的数据透视

时间:2011-10-06 10:04:12

标签: sql sql-server pivot

我有一个查询(从MyTable中选择[type],a,b,c,d,e)返回:

[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

我想转动数据,使其显示为:

[]     , [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   

这里有关于SQL的任何指针都会受到赞赏。

2 个答案:

答案 0 :(得分:1)

这样的东西?

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   

答案 1 :(得分:1)

我们需要的是:

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;

但由于类型号码未确定,我们必须动态

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)

但要小心,因为这个查询在技术上是注射的载体。