r/SQL • u/dettus_Xx_ • Aug 01 '26
PostgreSQL SQL Question: Rows into Columns without TABLEFUNC() or PIVOT?
Help me Reddit! I feel especially stupid today....
So, I have this table in my Postgresql Database:
event_id | color_scheme | count----------+--------------+-------1 | red | 61 | green | 31 | blue | 51 | yellow | 33 | red | 54 | red | 35 | red | 15 | blue | 2
And I would like to turn it sideways, so that I can see EASILY how many votes each color scheme for my event has gotten (and later JOIN it with another table... )
event_id | count_red | count_green | count_blue | count_yellow----------+-----------+-------------+------------+--------------1 | 6 | 3 | 5 | 33 | 5 | 0 | 0 | 04 | 3 | 0 | 0 | 05 | 1 | 0 | 2 | 0
The colors "red" "green" "blue" and "yellow" are fixed, and will never ever change.
I have done some googling, I found examples mentioning PIVOT and TABLEFUNC, but I cannot do this on the server because of reasons(tm).
The only way I can think of doing this is with a cascade of OUTER JOIN, but is there maybe a simpler solution?
View all comments
7
u/Imaginary__Bar Aug 01 '26 edited Aug 01 '26
Off the top of my head;
SELECT
event_id
, Max(If color_scheme = 'red' then count else 0) as count_red
, etc
, etc
Group by event_id
Edited to add: COUNT is a reserved keyword in SQL so you might have to use "count" (enclosed in double-quotes) in the SELECT statement.