数据准备
Create table If Not Exists Players (player_id int, group_id int);
Create table If Not Exists Matches (match_id int, first_player int, second_player int, first_score int, second_score int);
Truncate table Players;
insert into Players (player_id, group_id) values ('10', '2');
insert into Players (player_id, group_id) values ('15', '1');
insert into Players (player_id, group_id) values ('20', '3');
insert into Players (player_id, group_id) values ('25', '1');
insert into Players (player_id, group_id) values ('30', '1');
insert into Players (player_id, group_id) values ('35', '2');
insert into Players (player_id, group_id) values ('40', '3');
insert into Players (player_id, group_id) values ('45', '1');
insert into Players (player_id, group_id) values ('50', '2');
Truncate table Matches;
insert into Matches (match_id, first_player, second_player, first_score, second_score) values ('1', '15', '45', '3', '0');
insert into Matches (match_id, first_player, second_player, first_score, second_score) values ('2', '30', '25', '1', '2');
insert into Matches (match_id, first_player, second_player, first_score, second_score) values ('3', '30', '15', '2', '0');
insert into Matches (match_id, first_player, second_player, first_score, second_score) values ('4', '40', '20', '5', '2');
insert into Matches (match_id, first_player, second_player, first_score, second_score) values ('5', '35', '50', '1', '1');
需求
编写一个 SQL 查询来查找每组中的获胜者
输入
分析
输出
with t1 as (select *,casewhen first_score>second_score then first_playerwhen first_score<second_score then second_playerelse if(first_player<second_player,first_player,second_player)end as score_id,casewhen first_score>second_score then first_scoreelse second_scoreend as scorefrom Matches as m ,Players as pwhere m.first_player=p.player_id
),t2 as (select *,row_number() over (partition by group_id order by t1.score desc ) as rn1from t1
)
select group_id,score_id as player_id
from t2
where rn1=1
;