所以,我有喜欢points
列的表person1_id person2_id team_score
,你可以看到一个人能在person1_id
或person2_id
柱出现,因为玩家可以在多个团队,所以这个问题是如何获得最高average_score
前n位的球员被定义通过平均所有team_score的他|她参加了?像person_id average_score
?
我认为蒂姆的答案是一个很好的答案。但是,假设你有一个persons
表,你可以做到这一点没有union all
:
select p.person_id,
(select avg(team_score)
from points po
where p.person_id in (po.person1_id, po.person2_id)
) as average_score
from persons p
order by average_score desc
limit 5; -- or whatever
一个较为复杂的表达式可能是最有效的:
select p.person_id,
( (select sum(team_score)
from points po
where p.person_id = po.person1_id
) +
(select sum(team_score)
from points po
where p.person_id = po.person2_id
)
) /
nullif( (select count(*)
from points po
where p.person_id = po.person1_id
) +
(select count(*)
from points po
where p.person_id = po.person2_id
), 0
) as average_score
from persons p
order by average_score desc
limit 5;
究其原因,这是更有效的是,它可以利用索引对points(person1_id, team_score)
和points(person2_id, team_score)
。
一种方法是使用一个联合创建的所有球员和他们的分数单一逻辑列:
SELECT
person_id,
AVG(team_score) AS average_score
FROM
(
SELECT person1_id AS person_id, team_score FROM points
UNION ALL
SELECT person2_id, team_score FROM points
) t
GROUP BY
person_id
ORDER BY
AVG(team_score) DESC
LIMIT 10; -- e.g. for the top 10, but you may replace 10 with any value you want
你可能会用coalesce
功能,可以解决你的问题,是这样的:
SELECT
COALESCE(person1_id, person2_id) AS person_id,
AVG(team_score) as average_score
FROM points
GROUP BY COALESCE(person1_id, person2_id)
ORDER BY AVG(team_score)
这是怎么回事是COALESCE(col1, col2)
列表返回第一个非空列。只要你喜欢,你可以尽可能多列做到这一点。
首先,你需要得到所有不同的球员,然后将其加入qazxsw点表:
points
见select
d.id person_id,
avg(p.team_score) avgscore
from (
select person1_id id from points
union
select person2_id id from points
) d inner join points p
on (p.person1_id = d.id) or (p.person2_id = d.id)
group by d.id
order by avgscore desc
limit 3