简体   繁体   中英

Pivoting in Sybase SQL Query?

I am looking for a way to pivot the following results...

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

Into the following structure....

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

The number of columns is fixed (it will always be division/department/class). The query is intended for Sybase... have been unable to figure out how to achieve this sort of pivoting yet. Any advice?

The classic way to pivot to a fixed number of columns is like this:

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

You need some key to define the set of 3 rows. Then, you just self JOIN

So for data like this...

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

you'd have

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM