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 个分数需要与locationId
其他 3个不同
在这种情况下,我希望这个返回
eventId locationId score athlete
8739 73 48 matt
8734 73 46 matt
8788 73 45 matt
8789 6 43 matt
我已经尝试写出将使用 a 的查询,GROUP BY HAVING MIN(locationId) != MAX(locationId)
但我不确定如何在执行ORDER BY
and的同时完成该操作LIMIT
。
我也尝试过自加入,但我不确定如何根据s.score
and返回最佳结果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;
解决方案
您可以使用row_number
分析函数和limit
子句,包括self-join
如下一个
select locationId, score, athlete
from
(
select locationId, score, athlete, rn, rn2
from(
select *
from
(
with singles(locationId, score, athlete) as
(
select 73, 48, 'matt' union all
select 73, 46, 'matt' union all
select 73, 45, 'matt' union all
select 73, 44, 'matt' union all
select 73, 44, 'matt' union all
select 73, 43, 'matt' union all
select 6, 43, 'matt'
)
select row_number() over (partition by s.locationId order by s.score desc) as rn,
row_number() over (partition by s2.locationId order by s2.score desc) as rn2,
s.athlete, s.locationId, s.score
from singles s join singles s2
on s.score = s2.score
where s.athlete = 'matt'
) q1
order by score desc, rn, rn2
) q2
group by locationId, score
having sum(rn) <= sum(rn2)
order by rn, score desc
limit 4
) q3
order by score desc
推荐阅读
- selenium - Selenium:如何使用 C# 在 Chrome 中拖放
- angular - 为什么我的指令标签以角度反应形式出现在 dom 中
- html - 使弹性项目的内容滚动而不是使容器更高
- amazon-web-services - AWS 容器 (ECS) 与 AMI 和 Spot 实例
- vue.js - 如何将文本、按钮和图标传递给 v-radio 元素
- scanf - 使用 fscanf 时,被扫描的行之间发生了什么?
- angular - 延迟加载和路由到模块中的组件
- python - Plotly.py:填充为零,正/负不同颜色
- java - Java 11 包在不导出它的模块中声明
- pycharm - Pycharm - 添加键盘映射以从 SciView 保存绘图