Home > other >  how to group and pivot columns to values in SQL
how to group and pivot columns to values in SQL

Time:11-05

I have result from my query like this on PostgreSQL:

date depart blue_team red_team green_team
2023-08-11 south 2158 2832 2481
2023-08-11 east 6641 6714 6581
2023-08-11 north 1159 1512 1485
2023-08-11 west 8274 7131 8068

and i need to group team's in new column like team_type and sum values regard it.

So my prefered output should be like: enter image description here

my sql script:

with res as (
select
    date,
    depart,
    case
        when team_name = 'blue' then scores
    end blue_team,
    case
        when team_name = 'red' then scores
    end red_team,
    case
        when team_name = 'green' then scores
    end green_team
from results)
select
    date,
    depart,
    sum(blue_team) blue_team,
    sum(red_team) red_team,
    sum(green_team) green_team
from res
group by 1,2

CodePudding user response:

then simple union all would answer your question:

select date, depart, 'blue_team' as teamtype, blue_team as value from game_results
union all 
select date, depart, 'red_team' as teamtype, red_team as value from game_results
union all
select date, depart, 'green_team' as teamtype, green_team as value from game_results

or you can use unnest :

SELECT date, depart
, UNNEST(ARRAY['blue_team', 'red_team', 'green_team']) AS teamtype
, UNNEST(ARRAY[blue_team, red_team, green_team]) AS value
FROM game_results
date depart teamtype value
2023-08-11 south blue_team 2158
2023-08-11 east blue_team 6641
2023-08-11 north blue_team 1159
2023-08-11 west blue_team 8274
2023-08-11 south red_team 2832
2023-08-11 east red_team 6714
2023-08-11 north red_team 1512
2023-08-11 west red_team 7131
2023-08-11 south green_team 2481
2023-08-11 east green_team 6581
2023-08-11 north green_team 1485
2023-08-11 west green_team 8068

fiddle

  • Related