我正在寻找一种方法来调整以下结果......
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
列数是固定的(它将始终为division / department / class)。该查询适用于Sybase ...已经无法弄清楚如何实现这种旋转。有什么建议吗?
答案 0 :(得分:10)
转向固定数量的列的经典方法如下:
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
答案 1 :(得分:2)
您需要一些键来定义3行的集合。然后,你只需自己加入
所以对于像这样的数据......
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'