【问题标题】:Simple data pivot简单的数据透视
【发布时间】:2011-10-06 10:04:11
【问题描述】:

我有一个查询(从 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 的指针都将不胜感激。

【问题讨论】:

  • a、b、c、d、e 列是固定的,但可能有 X 行(类型)
  • 我只需要旋转表格,数据不需要分组,即[type]列中的类型永远是唯一的。

标签: sql sql-server pivot


【解决方案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;

但是由于 types 的数量是不确定的,所以我们必须动态地去做

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 types,这也会中断。见这里:msdn.microsoft.com/en-us/library/ms143432.aspx
  • 谢谢,这正是我现在想要的。我稍后会处理注射问题!
【解决方案2】:

这样的?

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)进行硬编码。我之前评论过类型是可变的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-24
  • 2012-08-06
  • 1970-01-01
  • 2014-12-10
  • 2020-05-09
相关资源
最近更新 更多