Tuesday, April 20, 2010

Pivot Table with SQL

One on my favourite technique with SQL is creating
pivot table. Here is an easy example using Postgres:

 
CREATE TABLE REVENUE
( YR int4,
QT chat,
REVENUE numeric);

 
insert into REVENUE values (2000, 'Q1', 240);
insert into REVENUE values (2000, 'Q2', 200);
insert into REVENUE values (2000, 'Q3', 230);
insert into REVENUE values (2000, 'Q4', 120);
insert into REVENUE values (2001, 'Q1', 320);
insert into REVENUE values (2001, 'Q2', 340);
insert into REVENUE values (2001, 'Q3', 290);
insert into REVENUE values (2001, 'Q4', 100);


Pivoting SQL:

 
SELECT
YR,
MAX(CASE WHEN QT = 'Q1' THEN REVENUE END) Q1,
MAX(CASE WHEN QT = 'Q2' THEN REVENUE END) Q2,
MAX(CASE WHEN QT = 'Q3' THEN REVENUE END) Q3,
MAX(CASE WHEN QT = 'Q4' THEN REVENUE END) Q4
FROM
REVENUE
GROUP BY YR

The result set going be pivoted
-------------------------------------------
YR  |  Q1  |  Q2  |  Q3  |  Q4
-------------------------------------------
2000   |  240   |  200    |  230    |  120
2001   |  320  |  340  |  290  |  100

No comments:

Post a Comment