Skip to content

Instantly share code, notes, and snippets.

@carlosromel
Forked from romansklenar/crosstab.sql
Last active October 31, 2017 18:31
Show Gist options
  • Select an option

  • Save carlosromel/7d6fe4bc4f8dc9185b7d1bd1a2506160 to your computer and use it in GitHub Desktop.

Select an option

Save carlosromel/7d6fe4bc4f8dc9185b7d1bd1a2506160 to your computer and use it in GitHub Desktop.
PostgreSQL "pivot table" example using tablefunc extension
CREATE EXTENSION tablefunc;
select *
from (values (2007, 1, 1000),
(2007, 2, 1500),
(2007, 7, 500),
(2007, 11, 1500),
(2007, 12, 2000),
(2008, 1, 1000),
(2009, 5, 2500),
(2009, 9, 800)) x (year, month, qty);
year | month | qty
------+-------+------
2007 | 1 | 1000
2007 | 2 | 1500
2007 | 7 | 500
2007 | 11 | 1500
2007 | 12 | 2000
2008 | 1 | 1000
2009 | 5 | 2500
2009 | 9 | 800
(8 rows)
select *
from crosstab($$
select year, month, qty
from (values (2007, 1, 1000),
(2007, 2, 1500),
(2007, 7, 500),
(2007, 11, 1500),
(2007, 12, 2000),
(2008, 1, 1000),
(2009, 5, 2500),
(2009, 9, 800)) x (year, month, qty)
order by 1
$$,
$$
select m from generate_series(1,12) m
$$
) as ("Year" int, "Jan" int, "Feb" int, "Mar" int, "Apr" int, "May" int, "Jun" int, "Jul" int, "Aug" int, "Sep" int, "Oct" int, "Nov" int, "Dec" int);
year | Jan | Feb | Mar | Apr | May | Jun | Jul | Aug | Sep | Oct | Nov | Dec
------+------+------+-----+-----+------+-----+-----+-----+-----+-----+------+------
2007 | 1000 | 1500 | | | | | 500 | | | | 1500 | 2000
2008 | 1000 | | | | | | | | | | |
2009 | | | | | 2500 | | | | 800 | | |
(3 rows)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment