mysql-按人选前4个成绩,但至少需要两个位置
作者:互联网
我有诸如
eventId locationId score athlete
8739 73 48 matt
8734 73 46 matt
8788 73 45 matt
8738 73 44 matt
8787 73 44 matt
8735 73 43 matt
8789 6 43 matt
我需要按人捕获前4个得分,但是前4个得分中至少有1个来自与其他3个不同的locationId
在这种情况下,我希望这个返回
eventId locationId score athlete
8739 73 48 matt
8734 73 46 matt
8788 73 45 matt
8789 6 43 matt
我试过写出将使用GROUP BY HAVING MIN(locationId)!= MAX(locationId)的查询,但是我不确定在完成ORDER BY和LIMIT的同时如何实现.
我也尝试过进行自我联接,但是我不确定如何根据s.score和score2返回最佳结果.
似乎步入正轨的自我联接的开始
SELECT s.eventid, s.locationid, athlete, score
, s2.eventid, s2.locationid, s2.athlete, score score2
FROM singles s
INNER JOIN singles s2 ON s.athlete = s2.athlete AND s.locationid != s2.locationid
WHERE s.athlete = 'matt'
ORDER BY score DESC;
解决方法:
因此,您真正想要的是前三名,然后是第一名,这至少保证了两个位置.
这是一个相当困难的条件,但是我认为这可以解决问题:
with s as (
select t.*,
row_number() over (partition by athlete order by score desc) as seqnum
from t
),
s3 as (
select s.*
from s
where seqnum <= 3
)
select *
from s3
union all
(select s.*
from s
where ( (select count(distinct locationid) from s3) > 1 and seqnum = 4 ) or
( (select count(distinct locationid) from s3) = 1 and
seqnum = (select min(seqnum)
from s
where locationid not in (select locationid from s3)
)
)
);
Here是db小提琴.
标签:mysql-8-0,sql,mysql 来源: https://codeday.me/bug/20191108/2007295.html