简单数据透视

3

我有一个查询(select [type], a, b, c, d, e from MyTable),它返回:

[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有任何建议,我们将不胜感激。


列a、b、c、d、e是固定的,但可能有X行(类型)。 - Mattl
我只需要旋转表格,数据不需要分组,即[type]列中的类型始终是唯一的。 - Mattl
2个回答

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、类型2、类型3)。我之前评论过类型是可变的。 - Mattl

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)

但要小心,因为这个查询在技术上是注入的向量。


值得注意的是,即使你将 @cols 和 @query 改为 nvarchar(max),对于超过 4096 种类型的任何内容都会出现问题。请参见这里:http://msdn.microsoft.com/en-us/library/ms143432.aspx - John N
谢谢,这正是我现在想要的。我稍后会处理注入问题! - Mattl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接