在同一张表中为2个不同的分组按功能创建2列

时间:2019-06-16 14:37:23

标签: mysql sql

我有以下mysql表:

team_id match_performance_rating    opponent_rating
1          500                    700
1          400                    625
2          600                    400
3          500                    525
2          400                    200

我希望能够衡量每支球队(1到3)的平均表现等级,具体取决于他们面对的是等级> 500还是小于500的对手,并将其与match_performance_rating比较。因此,我会将行的值与group by子句的值进行比较。

最终结果应该是这样的:

 team_id match_performance_rating  avg_pm_opp_over_500 avg_pm_opp_less_500
    1          500                    450                Null
    1          400                    450                Null
    2          600                    Null               500
    3          500                    500                Null
    2          400                    Null               500

我尝试执行某种类型的联合查询,但未创建额外的列:

select team_id, pm,pm2 from
(
select team_id,avg(match_performance_rating) as pm
from game_team_rating gtr
where gtr.opponent_rating > 500
group by team_id
union

select team_id as t2,avg(match_performance_rating) as pm2
from game_team_rating gtr
where gtr.opponent_rating < 500
group by team_id) as q

2 个答案:

答案 0 :(得分:1)

您可以通过条件汇总获得这些平均值,并将结果加入表格:

select 
  gtr.team_id,
  gtr.match_performance_rating,
  g.avg_pm_opp_over_500,
  g.avg_pm_opp_less_500
from game_team_rating gtr inner join (
  select 
    team_id,
    avg(case when opponent_rating > 500 then match_performance_rating end) avg_pm_opp_over_500,
    avg(case when opponent_rating <= 500 then match_performance_rating end) avg_pm_opp_less_500
  from game_team_rating
  group by team_id  
) g on g.team_id = gtr.team_id

请参见demo
结果:

| team_id | match_performance_rating | avg_pm_opp_over_500 | avg_pm_opp_less_500 |
| ------- | ------------------------ | ------------------- | ------------------- |
| 1       | 500                      | 450                 |                     |
| 1       | 400                      | 450                 |                     |
| 2       | 600                      |                     | 500                 |
| 3       | 500                      | 500                 |                     |
| 2       | 400                      |                     | 500                 |

答案 1 :(得分:0)

使用窗口函数(在MySQL 8+中可用):

select gtr.*
       avg(case when gtr.opponent_rating > 500 then match_performance_rating end) over (partition by gtr.team_id) as pm_over_500,
       avg(case when gtr.opponent_rating < 500 then match_performance_rating end) over (partition by gtr.team_id) as pm_under_500
from game_team_rating gtr;
相关问题