How to pivot or crosstab in postgresql without writing a function?

samthebrand picture samthebrand · May 11, 2018 · Viewed 8.7k times · Source

I have a dataset that looks something like this:

gotta pivot

I'd like to aggregate all co values on one row, so the final result looks something like:

enter image description here

Seems pretty easy, right? Just write a query using crosstab, as suggested in this answer. Problem is that requires that I CREATE EXTENSION tablefunc; and I don't have write access to my DB.

Can anyone recommend an alternative?

Answer

Lukasz Szozda picture Lukasz Szozda · May 11, 2018

Conditional aggregation:

SELECT co,
  MIN(CASE WHEN ontology_type = 'industry' THEN tags END) AS industry,
  MIN(CASE WHEN ontology_type = 'customer_type' THEN tags END) AS customer_type, 
  -- ...
FROM tab_name
GROUP BY co