I have a table with the following fields: id, opp1, opp2, opp1_votes, opp2_votes.
If one of the opps have more votes than another so we consider that he won. How can I get opp with most wins from this table?
I have a table with the following fields: id, opp1, opp2, opp1_votes, opp2_votes.
If one of the opps have more votes than another so we consider that he won. How can I get opp with most wins from this table?
SELECT opp, sum(win) wins FROM (
SELECT opp1 opp, CASE WHEN opp1_votes > opp2_votes THEN 1 ELSE 0 END win
FROM otable
UNION ALL
SELECT opp2 opp, CASE WHEN opp2_votes > opp1_votes THEN 1 ELSE 0 END win
FROM otable
) A
GROUP BY opp
ORDER BY sum(win) DESC LIMIT 1
This query will find the number of wins for each user, and order them in a descending order (so the one with most wins will be the first row):
SELECT winner, COUNT(*)
FROM
(
SELECT opp1 AS winner FROM table
WHERE opp1_votes > opp2_votes
UNION ALL
SELECT opp2 AS winner FROM table
WHERE opp2_votes > opp1_votes
)
GROUP BY winner
ORDER BY COUNT(*) DESC
Explanation of the query:
Notes:
SELECT TOP 1 winner, ...
or finish with LIMIT 1
, but as far as I know it will not save computation time in the general case, so I'll leave it.Does this do what you want it to?
select top 1 opp1,
(select count(*)
from table i
where i.opp1 = o.opp1 and i.opp1votes > i.opp2votes) as wins
from table o
order desc by wins
SELECT
CASE WHEN opp1_votes > opp2_votes THEN opp1 ELSE opp2 END as winner,
COUNT(*)
FROM table
GROUP BY CASE WHEN opp1_votes > opp2_votes THEN opp1 ELSE opp2 END
ORDER BY COUNT(*) DESC
This little query will get you all the winners and the number of times he's won in descending order:
SELECT
(CASE WHEN `opp1_votes`>`opp2_votes` THEN `opp1` ELSE `opp2` END) `winner`,
COUNT(*) AS `no_of_times`
FROM `matches`
GROUP BY `winner`
ORDER BY `no_of_times` DESC
What we are doing here is:
winner
column and vice versaIf you want just the person with most number of wins you can add LIMIT 1
to the end of the query or you can wrap the above query and select max(no_of_times) from it like below:
SELECT `winner`, MAX(`no_of_times`) AS `no_of_times` FROM (
SELECT
(CASE WHEN `opp1_votes`>`opp2_votes` THEN `opp1` ELSE `opp2` END) `winner`,
COUNT(*) AS `no_of_times`
FROM `matches`
GROUP BY `winner`
ORDER BY `no_of_times` DESC
) AS `winners`