我在 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
然后简单的 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 |