2011-11-13 60 views
3

我正在尋找一種方式來轉動的結果如下...在Sybase SQL查詢中旋轉嗎?

ID | Group_Level | Group_Values 
1 | Division | Value 1 
2 | Department | Value 2 
3 | Class  | Value 3 

爲以下結構....

ID | Division | Department | Class 
1 | Value 1 | Value 2 | Value 3  
2 | Value 1 | Value 2 | Value 3 

列的數量是固定的(它總是會分裂/科/班)。該查詢用於Sybase ...一直未能弄清楚如何實現這種類型的透視。有什麼建議?

+0

什麼鏈接任何一組3列,你想變成列? – gbn

回答

2

您需要一些鍵來定義3行的集合。然後,你就自我JOIN

因此,對於這樣的數據...

ID | GroupID | Group_Level | Group_Values 
1 | 1 | Division | Value 1 
2 | 1 | Department | Value 2 
3 | 1 | Class  | Value 3 
4 | 2 | Division | Value 1 
5 | 2 | Department | Value 2 
6 | 2 | Class  | Value 3 

你必須

SELECT 
    Div.GroupID, Div.Group_Values, Dept.Group_Values, Cl.Group_Values 
FROM 
    MyTable Div 
    JOIN 
    MyTable Dept ON Div.GroupID = Dept.GroupID 
    JOIN 
    MyTable Cl ON Div.GroupID = Cl.GroupID 
WHERE 
    Div.Group_Level = 'Division' 
    AND 
    Dept.Group_Level = 'Department' 
    AND 
    Cl.Group_Level = 'Class' 
9

經典的方式轉動一個固定的列數是這樣的:

select id, 
max (case when group_level = 'Division' then Group_Values else null end) Division, 
max (case when group_level = 'Department' then Group_Values else null end) Department, 
max (case when group_level = 'Class' then Group_Values else null end) Class 
from 
YourTable 
group by id