Home » Php » php – SQL – Combine two COUNT with different WHERE causes and GROUP BY the users names

php – SQL – Combine two COUNT with different WHERE causes and GROUP BY the users names

Posted by: admin February 25, 2020 Leave a comment

Questions:

I’m trying hard to find a solution to this one but I can’t see a way to do it.

I am inserting kills made in a game and I am recording the killer, his clan, the victim and the victim’s clan so my database looks like this,

killer | killerClan | victim | victimClan
-----------------------------------------
User_A |   Team_A   | User_B |   Team_B
User_C |   Team_B   | User_A |   Team_A
User_B |   Team_B   | User_A |   Team_A
User_D |   Team_A   | User_C |   Team_B
User_C |   Team_B   | User_A |   Team_A
User_B |   Team_B   | User_D |   Team_A
User_D |   Team_A   | User_C |   Team_B

The same user can be shown as a killer or a victim depends if he killed somebody or died by somebody.

I can show the total kills of users of a specific Clan by,

SELECT killer AS username, COUNT(killer) AS kills FROM master_tracker
WHERE killerClan = "Team_A"
GROUP BY killer
ORDER BY kills DESC

and by the same logic, I can show the total deaths of users of a specific Clan by,

SELECT victim AS username, COUNT(victim) AS deaths FROM master_tracker
WHERE victimClan = "Team_A"
GROUP BY victim
ORDER BY deaths DESC

But… what I want to do is to combine the two queries and show the users’ kills and deaths group by their name which can be found in killer column in the first case and victim column in the second case so ultimately to be able to present their Kills/Deaths Ratio but I need different WHERE causes because in first case their Clan can be found as killerClan and in the second case as victimClan.

Goal is to have a result like that.

username | kills | deaths | kdRatio
-----------------------------------
 User_D  |   2   |    1   |    1
 User_A  |   1   |    3   |   -2

All suggestions are welcomed.

How to&Answers:

You can use union all and aggregation:

select 
    username, 
    sum(kills) kills, 
    sum(deaths) deaths,
    sum(kills) - sum(deaths) kdRatio
from (
    select killer username, count(*) kills, 0 deaths 
    from master_tracker 
    where killerClan = 'TeamA'
    group by killer
    union all 
    select victim, 0, count(*) 
    from master_tracker 
    where victimClan = 'TeamA'
    group by victim
) t
group by username
order by kdRatio desc