在Sybase SQL查询中如何进行数据透视?

6

我正在寻找一种方法来转置以下结果...

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……尚未找出如何实现这种透视的方法。 有什么建议吗?

列数固定,始终为division/department/class。查询是针对Sybase的,但目前还没有弄清如何进行透视操作。请问是否有相关建议?

你想要将任意一组3行转换为列,有什么联系? - gbn
2个回答

15

将数据透视为固定列数的经典方法如下:

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

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'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接