使用Pivot的SQL查询

时间:2011-08-29 11:01:12

标签: sql sql-server sql-server-2005 sql-server-2008

我有一张表格如下:

PriorityText  Priority  LoRes   Partial  Unknown  N_A      HiRes
------------------------------------------------------------------
Very High     5         0.0612  0.0000   0.0612   0.0612   0.2041
High          4         0.1429  0.0000   0.1633   0.0000   0.1633
Medium        3         0.0000  0.0000   0.1020   0.0000   0.0408
Low-Medium    2         0.0000  0.0000   0.0000   0.0000   0.0000
Low           1         0.0000  0.0000   0.0000   0.0000   0.0000

我想将表转换成这个:

PriorityText  Low  Low-Medium  Medium  High    Very High
--------------------------------------------------------
Priority      1    2           3       4       5
LoRes         0    0           0       0.1429  0.0612
Partial       0    0           0       0       0
Unknown       0    0           0.102   0.1633  0.0612
N_A           0    0           0       0       0.0612
HiRes         0    0           0.0408  0.1633  0.2041

我正在使用SQL 2008.我无法使用SQL语法来对数据执行调整。

有人可以分享一个SQL代码片段来解决这个问题吗?

我已经使用以下方法成功转动了一行,但我不知道如何让它完成所有行。

SELECT VeryHigh AS VeryHigh, 
       High AS High, 
       Medium AS Medium, 
       [Low-Medium] AS [Low-Medium], 
       Low AS Low
 FROM  (SELECT [PriorityText], [LoRes] FROM @tbTemp) p
PIVOT (SUM(LoRes) FOR [PriorityText] in ([VeryHigh], [High], [Medium], [Low-Medium], [Low])) pvt

我表中的测试数据如下:

Priority PriorityText   LoRes   Partial  Unknown   N_A    HiRes
1        VeryHigh       0.05    11       54        0      9
2        High           0.14    22       54        0      3
3        Medium         0.07    33       65        0      7
4        Low-Medium     0.01    44       87        0      4
5        Low            0       55       9         0      0
NULL     NULL           NULL    NULL     NULL      NULL   NULL

感谢您的帮助!!

1 个答案:

答案 0 :(得分:0)

不确定你可以做多少硬编码,但你想要做的是用列转置行。

SELECT p.[Type] as 'PriorityText', Low, [Low-Medium], Medium,High,[VeryHigh]
FROM (SELECT PriorityText, [Holder],[Type]
      FROM (SELECT PriorityText,Priority,LoRes,[Partial],Unknown,N_A,HiRes
              FROM Test) as sq_source
      UNPIVOT ([Holder] FOR [Type] IN
        (Priority,LoRes,[Partial],Unknown,N_A,HiRes)) as sq_up
     ) as sq 
 PIVOT (
    MIN([Holder])
    FOR PriorityText IN
       (VeryHigh,High,Medium,[Low-Medium],Low)
       ) as p
    order by CASE p.[Type] WHEN 'Priority' THEN 1
    WHEN 'LoRes' THEN 2
    WHEN 'Partial' THEN 3
    WHEN 'Unknown' THEN 4
    WHEN 'N_A' THEN 5
    ELSE 6 END ASC;

这应该可以满足您的需求。有一点需要注意,这只适用于列:

  • 优先级
  • LoRes
  • 部分
  • 未知
  • N_A
  • 高分辨率

具有相同的数据类型(在我的测试中它是十进制(5,4))。如果你的不同,那么你需要进行初始选择并将它们转换为通用数据类型并将其用作sq_source。