我有一个包含以下字段的表:id,opp1,opp2,opp1_votes,opp2_votes。
如果其中一个opps的票数高于另一个,那么我们认为他赢了。如何从这张桌子获得最多的胜利?
答案 0 :(得分:4)
此查询将查找每个用户的获胜次数,并按降序排序(因此获胜次数最多的是第一行):
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
查询说明:
注意:
SELECT TOP 1 winner, ...
开始或以LIMIT 1
结束,但据我所知,它不会节省一般情况下的计算时间,所以我'留下它。答案 1 :(得分:0)
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
答案 2 :(得分:0)
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
答案 3 :(得分:0)
这个小小的查询将为您赢得所有获胜者以及他以降序获胜的次数:
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
我们在这里做的是:
winner
列中的opp1,反之亦然如果你只想要获胜次数最多的人,可以在查询结尾添加LIMIT 1
,或者你可以包装上面的查询并从中选择max(no_of_times),如下所示:
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`
答案 4 :(得分:-2)
这是否符合您的要求?
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