Pivoting in Sybase SQL Query?

Borophyll picture Borophyll · Nov 13, 2011 · Viewed 18.9k times · Source

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?

Answer

Lord Peter picture Lord Peter · Nov 13, 2011

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