当前位置:网站首页>SQL: Championship winner

SQL: Championship winner

2022-06-09 08:32:00 Jieyou grocery store Q

 Write a  SQL  Query to find the winners in each group .

 The winner of each group is the player with the highest cumulative score in the group . If there is a draw ,player_id  The youngest player wins .

 Each line is the record of a game , 
first_player  and  second_player  Indicates the player of the game  id.
first_score  and  second_score  respectively  first_player  and  second_player  Score of .
 You can assume , In every game , The players belong to the same group .

CREATE TABLE players ( player_id INT, group_id INT );
CREATE TABLE matches (
	match_id INT,
	first_player INT,
	second_player INT,
	first_score INT,
	second_score INT 
);

REPLACE INTO players ( player_id, group_id ) VALUES
( 10, 2 ),( 15, 1 ),( 20, 3 ),( 25, 1 ),( 30, 1 ),( 35, 2 ),( 40, 3 ),( 45, 1 ),( 50, 2 );

REPLACE INTO matches ( match_id, first_player, second_player, first_score, second_score ) VALUES
( 1, 15, 45, 3, 0 ),( 2, 30, 25, 1, 2 ),( 3, 30, 15, 2, 0 ),( 4, 40, 20, 5, 2 ),
( 5, 35, 50, 1, 1 );

 Insert picture description here
 Insert picture description here

Method 1

Every game , Each player has accumulated scores , Then the highest score is the highest score of the group

SELECT
	group_id,
	player_id
from 
	(
	SELECT
		group_id,
		player_id,
		rank() over ( PARTITION BY group_id ORDER BY sum( IF ( player_id = first_player, first_score, second_score ) ) DESC, player_id ) rn 
	FROM
		matches a
		LEFT JOIN players b ON a.first_player = b.player_id 
		OR a.second_player = b.player_id 
	GROUP BY
		group_id,
		player_id
	) t
WHERE rn =1

 Insert picture description here

原网站

版权声明
本文为[Jieyou grocery store Q]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/160/202206090825279388.html