Monday, August 16, 2010

PIVOT in SQL Server

Prior to SQL 2005 I have to explicitly define a query to do a pivot like below

select work_group, sum(case when days <= 10 then 1 else 0 end) as LT3,sum(case when days > 10 and days <15> 15 then 1 else 0 end) as [GT 15] from view_1 group by work_group

In SQL 2005 there is another way to do it.

select work_group,LT3,[3 to 15],[GT 15] from (

SELECT case_id,work_group, CASE WHEN days <= 10 THEN 'LT3' WHEN days >10 and days < 15 THEN '3 to 15' when days >15 then 'GT 15' END AS days

FROM view_1 ) as rawdata

pivot (

count(case_id) for days in (LT3,[3 to 15],[GT 15])) as pvt

The latter looked more complicated but both worked exactly the same. However, the latter is sorted on work_group automatically.

The example is more interesting when "days" is already parsed according to its grouping. You just need to define "select case_id, work_group, days from view_1". Coupled with the fact that "select work_group,LT3,[3 to 15],[GT 15]" can be shortened to just "select *". You get the following

select * from ( SELECT case_id,work_group, days FROM view_1 ) as rawdata pivot ( count(case_id) for days in (LT3,[3 to 15],[GT 15])) as pvt

Don't you think that the above code is much simpler to write than prior SQL 2005 codes? You just can't make it simpler with the prior SQL2005 series.

No comments:

Post a Comment