SQL Server:行到具有大小写的列

时间:2014-04-10 16:33:15

标签: sql sql-server case

我有一个包含2列的表:

CREATE TABLE Prop_Cl 
(
 Id int, 
 ClId int
);
INSERT INTO Prop_Cl
(Id, ClId)
VALUES
(1, 1111111),
(1, 1111112),
(1, 1111113),
(2, 2222221),
(3, 3333331),
(3, 3333332);



ID     CLID  
1      1111111  
1      1111112  
1      1111113  
2      2222221  
3      3333331  
3      3333332  

我试图以这种方式展示这张桌子:

ID  CLIENT 1  CLIENT 2  CLIENT 3  CLIENT 4  
1   1111111   1111112   1111113   0  
2   2222221   0         0         0  
3   3333331   3333332   0         0 

发表声明:

SELECT p.Id, 
CASE WHEN (ROW_NUMBER() OVER(PARTITION BY p.Id ORDER BY p.Id)) = 1 THEN p.ClId ELSE 0 END  AS 'Client 1',
CASE WHEN (ROW_NUMBER() OVER(PARTITION BY p.Id ORDER BY p.Id)) = 2 THEN p.ClId ELSE 0 END  AS 'Client 2',
CASE WHEN (ROW_NUMBER() OVER(PARTITION BY p.Id ORDER BY p.Id)) = 3 THEN p.ClId ELSE 0 END  AS 'Client 3',
CASE WHEN (ROW_NUMBER() OVER(PARTITION BY p.Id ORDER BY p.Id)) = 4 THEN p.ClId ELSE 0 END  AS 'Client 4'
FROM Prop_Cl p

但我得到了这个结果:

ID  CLIENT 1    CLIENT 2    CLIENT 3    CLIENT 4
1   1111111     0           0           0
1   0           1111112     0           0
1   0           0           1111113     0
2   2222221     0           0           0
3   3333331     0           0           0
3   0           3333332     0           0

由于我的Sql Server实现,我无法使用PIVOT功能。 每个ID最多有4个客户端。 有任何想法吗? SQL Fiddle

1 个答案:

答案 0 :(得分:2)

我会稍微改变语法,使用聚合函数和类似于的子查询:

select id,
  max(case when seq = 1 then ClId else 0 end) Client1,
  max(case when seq = 2 then ClId else 0 end) Client2,
  max(case when seq = 3 then ClId else 0 end) Client3,
  max(case when seq = 4 then ClId else 0 end) Client4
from
(
  select Id, ClId,
    ROW_NUMBER() OVER(PARTITION BY Id ORDER BY Id) seq
  from Prop_Cl
) s
group by id;

请参阅SQL Fiddle with Demo