如何在 SQL 中对列进行分组和透视列到值

问题描述 投票:0回答:1

我在 PostgreSQL 上得到这样的查询结果:

日期 出发 蓝色_团队 红队 绿色团队
2023-08-11 2158 2832 2481
2023-08-11 6641 6714 6581
2023-08-11 1159 1512 1485
2023-08-11 西 8274 7131 8068

我需要将团队分组到像

team_type
这样的新列中,并且总和值会考虑它。

所以我喜欢的输出应该是这样的:

我的sql脚本:

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
sql postgresql pivot
1个回答
0
投票

然后简单的 union all 就可以回答你的问题了:

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
日期 出发 团队类型 价值
2023-08-11 蓝色_团队 2158
2023-08-11 蓝色_团队 6641
2023-08-11 蓝色_团队 1159
2023-08-11 西 蓝色_团队 8274
2023-08-11 红队 2832
2023-08-11 红队 6714
2023-08-11 红队 1512
2023-08-11 西 红队 7131
2023-08-11 绿色团队 2481
2023-08-11 绿色团队 6581
2023-08-11 绿色团队 1485
2023-08-11 西 绿色团队 8068

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.