Skip to content
Advertisement

Combine SQL queries with different WHERE causes

I have written a database with game stats, featuring winner, loser, and money won. I’m now trying to make stats for it.

See database here

I’m trying to make stats for these games, etc number of wins/losses for player, and money lost and money won.

Till now I have found three queries to achieve this.

SELECT COUNT(winner) AS wins, COUNT(loser) AS losses 
FROM coinflipper_games 
WHERE winner = "dba92393-5bbd-365f-8fe7-55be2707caf3" 
   OR loser = "dba92393-5bbd-365f-8fe7-55be2707caf3"

SELECT SUM(money) 
FROM coinflipper_games 
WHERE winner = "dba92393-5bbd-365f-8fe7-55be2707caf3"

SELECT SUM(money) 
FROM coinflipper_games 
WHERE loser = "dba92393-5bbd-365f-8fe7-55be2707caf3"

The problem is, it’s in no way effective using three queries, so I’m trying to reduce this to one. Does anyone have any idea what I can do?

Advertisement

Answer

Use conditional aggregation as follows:

SELECT SUM(case when winner='dba92393-5bbd-365f-8fe7-55be2707caf3' then 1 else 0 end) AS wins, 
       SUM(case when loser='dba92393-5bbd-365f-8fe7-55be2707caf3' then 1 else 0 end)  AS losses,
       SUM(CASE WHEN winner = 'dba92393-5bbd-365f-8fe7-55be2707caf3' THEN money ELSE 0 END) as winnings,
       SUM(CASE WHEN loser = 'dba92393-5bbd-365f-8fe7-55be2707caf3' THEN money ELSE 0 END) as losings
  FROM coinflipper_games
 WHERE winner='dba92393-5bbd-365f-8fe7-55be2707caf3' 
    OR loser='dba92393-5bbd-365f-8fe7-55be2707caf3'
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement