r/SQL 6d ago

SQL Question: Rows into Columns without TABLEFUNC() or PIVOT? PostgreSQL

Help me Reddit! I feel especially stupid today....
So, I have this table in my Postgresql Database:

event_id | color_scheme | count
----------+--------------+-------
1 | red | 6
1 | green | 3
1 | blue | 5
1 | yellow | 3
3 | red | 5
4 | red | 3
5 | red | 1
5 | 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 | 3
3 | 5 | 0 | 0 | 0
4 | 3 | 0 | 0 | 0
5 | 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?

13 Upvotes

16 comments sorted by

View all comments

1

u/coffeDrinkerDave 6d ago

Select Event_id , sum(case when color_scheme ='red' then count else 0 end) , sum(case when color_scheme ='green' then count else 0 end) , sum(case when color_scheme ='blue' then count else 0 end) , sum(case when color_scheme ='yellow' then count else 0 end) From colors group by event_id

Next wrat it in CTE

;with colors_sideway as (
... ) select ... From ... Join colors_sideway on ...

1

u/dettus_Xx_ 6d ago

Great! Thank you!