Skip to content

Instantly share code, notes, and snippets.

@knmkr
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save knmkr/4f82097a99dca8423104 to your computer and use it in GitHub Desktop.

Select an option

Save knmkr/4f82097a99dca8423104 to your computer and use it in GitHub Desktop.
Convert rows to cols by crosstab()
CREATE EXTENSION IF NOT EXISTS tablefunc;
CREATE TEMP TABLE my_rows (age integer, gender varchar, val integer);
INSERT INTO my_rows VALUES (10, 'M', 11), (10, 'W', 12), (10, 'A', 13);
INSERT INTO my_rows VALUES (20, 'M', 21), (20, 'W', 22);
INSERT INTO my_rows VALUES (30, 'A', 33);
-- rows
SELECT * FROM my_rows;
-- age | gender | my_value
-- -----+--------+----------
-- 10 | M | 11
-- 10 | W | 12
-- 10 | A | 13
-- 20 | M | 21
-- 20 | W | 22
-- 30 | A | 33
-- (6 rows)
-- cols
SELECT * FROM crosstab('SELECT * FROM my_rows ORDER BY 1,2', $$VALUES ('M'::varchar), ('W'::varchar), ('A'::varchar)$$)
AS ct(age integer, M_val integer, W_val integer, A_val integer);
-- age | m_value | w_value | a_value
-- -----+---------+---------+---------
-- 10 | 11 | 12 | 13
-- 20 | 21 | 22 |
-- 30 | | | 33
-- (3 rows)
-- http://stackoverflow.com/questions/3002499/postgresql-crosstab-query
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment