Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL query to aggregate result of a column comparison

I have a SQL (Postgres) data structure that represents games for a group of matches. Table below shows that there have been 3 matches played (each consisting of either 2 or 3 games).

match_id player_one player_two p1_game_result p2_game_result
1 player1 player2 12 10
1 player1 player2 3 11
1 player1 player2 5 9
2 player1 player3 11 2
2 player1 player3 11 1
3 player2 player4 11 6
3 player2 player4 7 11
3 player2 player4 9 5

I want to group it by matchID to the following result table – each row should represent single match that will show how many games has each player won (which simply mean which out of 2 results column will be greater).

match_id player_one player_two p1_games_won p2_games_won
1 player1 player2 1 2
2 player1 player3 2 0
3 player2 player4 2 1

I’m aware how GROUP BY works, but I’m not able to use aggregate function that will apply required condition based on column values.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Query below counts games for each match only, without distinguishing how many games has each player won in a match.

SELECT
    g.match_id,
    g.player_one,
    g.player_two,
    count(*) as games_count
FROM games g
GROUP BY
    g.match_id,
    g.player_one,
    g.player_two;

Any help will be appreciated.

>Solution :

Use a CASE statement inside your COUNT to compare the two columns e.g.

SELECT
    g.match_id,
    g.player_one,
    g.player_two,
    count(CASE WHEN p1_game_result > p2_game_result THEN 1 END) as p1_games_won,
    count(CASE WHEN p2_game_result > p1_game_result THEN 1 END) as p_games_won
FROM games g
GROUP BY
    g.match_id,
    g.player_one,
    g.player_two;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading