Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 514
samthebrand Avatar asked Dec 24 '22 07:12

samthebrand


1 Answers

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
like image 178
Lukasz Szozda Avatar answered Jan 02 '23 09:01

Lukasz Szozda