Skip to content

Instantly share code, notes, and snippets.

@barsbek
Created March 20, 2018 06:45
Show Gist options
  • Save barsbek/caacbf7e08ac366fb9c7d97ff32099c6 to your computer and use it in GitHub Desktop.
Save barsbek/caacbf7e08ac366fb9c7d97ff32099c6 to your computer and use it in GitHub Desktop.
postgresql: pivot table according to row_names, categories and values
select * from crosstab($$
select row_name, some_category, some_value --only 3 columns!
from some_table
$$, $$values(category1), (category2), ..., (categoryn)$$ -- same can be achieved by selecting distinct values
) as g(RowName type, Category1 type, Category2 type, ..., CategoryN type);
-- type of CategoryN should be the same as type of value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment