2014-04-10 78 views
0

我有2列的表格:SQL服務器:行到列與案例

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

你是什麼意思的,因爲你的SQL,你不能用做支點服務器實現? – pquest

+0

我不確定,但是我的MS SQL Server 2008有一個sql server 2000的實現 – andmike

回答

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

+0

謝謝。它看起來太棒了! – andmike