建议在SQL Server中修改数据透视查询以获得所需的输出

时间:2016-04-25 21:53:57

标签: sql sql-server tsql pivot

我有以下数据:

------------------------------------------------
DestinationSite     SourceSite    Dist      Rank
------------------------------------------------
CZ_0                 PFC        2717.64      1
CZ_0                 WFC        3218.22      2
CZ_0                 OFC        3971.14      3
CZ_0                 FFC        4226.69      4
CZ_10001             FFC        64.13        1
CZ_10001             OFC        564.11       2
CZ_10001             WFC        2511.03      3
CZ_10001             PFC        2867.75      4

我想将其更改为以下格式:

------------------------------------------------
DestinationSite   Pref1   Pref2   Pref3   Pref4
------------------------------------------------
CZ_0               PFC     WFC     OFC     FFC
CZ_10001           FFC     OFC     WFC     PFC

我写了如下查询:

select DestinationSite, [1] as Pref1, [2] as Pref2, [3] as Pref3, [4] as Pref4
from Table1 a
pivot (max(SourceSite) for Rank in ([1],[2],[3],[4])) as b
order by DestinationSite;

但它给出了如下输出,与我的要求不同:

-------------------------------------------------
DestinationSite     Pref1   Pref2   Pref3   Pref4
-------------------------------------------------
CZ_0                PFC     NULL    NULL    NULL
CZ_0                NULL    WFC     NULL    NULL
CZ_0                NULL    NULL    OFC     NULL
CZ_0                NULL    NULL    NULL    FFC
CZ_10001            FFC     NULL    NULL    NULL
CZ_10001            NULL    OFC     NULL    NULL
CZ_10001            NULL    NULL    WFC     NULL
CZ_10001            NULL    NULL    NULL    PFC

需要有关如何修改查询以获得所需输出的建议。感谢。

1 个答案:

答案 0 :(得分:1)

试试这个:

创建表

create table Destination 
(
 DestinationSite varchar(10),
 SourceSite varchar(3),
 dist decimal(18,2),
 [rank] tinyint
 )

插入数据

insert into Destination values

('CZ_0',    'PFC', 2717.64,   1),
('CZ_0',    'WFC', 3218.22,   2),
('CZ_0',    'OFC', 3971.14,   3),
('CZ_0',    'FFC', 4226.69,   4),
('CZ_10001','FFC', 64.13,     1),
('CZ_10001','OFC', 564.11,    2),
('CZ_10001','WFC', 2511.03,   3),
('CZ_10001','PFC', 2867.75,   4)

枢轴

; with cte
as
(
  select
         DestinationSite,
         SourceSite,
         [rank] as r
   from Destination

)

SELECT DestinationSite,[1] as Pref1 ,[2] as Pref2,[3] as Pref3 ,[4] as Pref4 FROM cte
PIVOT(max(SourceSite) FOR r IN ([1],[2],[3],[4])  ) AS P

结果

------------------------------------------------
DestinationSite   Pref1   Pref2   Pref3   Pref4
------------------------------------------------
CZ_0               PFC     WFC     OFC     FFC
CZ_10001           FFC     OFC     WFC     PFC