我正在尝试从下表(示例)构建SQL查询:
Example of table with name "performances"
这是运动表演的表格。我想根据每个学科的表格和一个或多个类别的集合选择最佳表现。每位运动员的成绩应该只有一次,尽管他的最佳表现值是表现表的两倍或更多。
Here is expected result from table "performances"
实际上我有这个SQL查询,但是从子查询加入所有具有最佳值的行,最好是Athle_id:
SELECT
p.athlete_id, p.value
FROM
(SELECT athlete_id, MAX(value) AS best FROM performances
WHERE discipline_id = 32 AND category_id IN (1,3,5,7,9)
GROUP BY athlete_id) f
INNER JOIN performances p
ON p.athlete_id = f.athlete_id AND p.conversion = f.best
ORDER BY p.value DESC, p.created

请问,我怎样才能为每位运动员加入一排,这位运动员创造了最早的属性?
答案 0 :(得分:0)
要根据最大值athlete
获取每discipline
个value
的单行,您可以执行自我左连接,处理平局情况或单athlete
如果有多个行具有相同的最大值,则可以使用case语句选择具有最早日期的行
select a.*
from performances a
left join performances b
on a.discipline_id = b.discipline_id
and a.athlete_id = b.athlete_id
and case when a.value = b.value
then a.created > b.created
else a.value < b.value
end
where b.discipline_id is null
此外,您可以在where子句中添加过滤器
and a.discipline_id = 32
and a.category_id IN (1,3,5,7,9)
答案 1 :(得分:0)
您不必使用联接,可以使用window function:
执行此操作SELECT
p.athlete_id,
p.value
FROM
(
SELECT
athlete_id,
value,
ROW_NUMBER() over (partition by athlete_id order by value desc, created) rowid
FROM
performances
WHERE
discipline_id = 32 AND
category_id IN (1,3,5,7,9)
) p
where
p.rowid = 1
答案 2 :(得分:0)
非常感谢,伙计们。在你的答案后,我终于找到了解决方案。
SELECT r.* FROM
(SELECT p.athlete_id, p.conversion, MIN(p.created) AS created FROM
(SELECT athlete_id, MAX(conversion) AS best
FROM performances
WHERE discipline_id = 32 AND category_id IN (1,3,5,7,9)
GROUP BY athlete_id) f
INNER JOIN performances p ON p.athlete_id = f.athlete_id AND p.conversion = f.best
GROUP BY p.athlete_id) w INNER JOIN performances r
ON w.athlete_id = r.athlete_id AND w.conversion = r.conversion
AND ((w.created = r.created) OR (w.created IS NULL AND r.created IS NULL))
ORDER BY r.conversion DESC, r.created
&#13;