Name Day Points Brian 1 6 Tom 1 11 Freddy 1 7 Kim 2 10 Sandra 2 1 Brian 2 3
我需要知道谁赢得了第二名的最大利润 - 但仅限于同一天的人之间。
因此,如果做得好,它会告诉我Kim已经获得了最大的利润。
我不太清楚如何处理这个问题。
答案 0 :(得分:1)
select
first_place.name,
max_points-max(points) as max_margin
from the_table
inner join
(select name, day, max(points) as max_points
from the_table group by day) as first_place
on the_table.day=first_place.day
where the_table.points<max_points
group by the_table.day
order by max_margin desc limit 1 ;
答案 1 :(得分:0)
这需要通过两个子查询完成...最内部获得一天的最高分,然后,在第一个位置找到下一个最高的scrore,然后找到边距...但是,由于您的名称样本数据,不考虑唯一的名称,否则将由某个内部ID ...在您的示例数据中说“Brian”...两天都是相同的Brian,还是不同的人。另外,如果两个人以11分并列第一名,那么我的查询将在现在“第三”位置的边缘之前的第一位显示两个人作为检测到的边缘。您可能需要修改一些以适应所描述的条件..
SELECT
FS.Day,
FS.FirstPlace,
FS.SecondPlace,
FS.FirstPlace - FS.SecondPlace as Margin,
G.Name
FROM
( SELECT G2.Day,
FirstPlace.FirstPlacePoints FirstPlace,
MAX( G2.Points ) as SecondPlace
FROM
Games G2,
( SELECT Day,
MAX( Points ) as FirstPlacePoints
FROM
Games
GROUP BY
Day ) FirstPlace
WHERE
G2.Day = FirstPlace.Day
AND G2.Points < FirstPlace.FirstPlacePoints
GROUP BY
1, 2 ) as FS,
Games G
WHERE
FS.Day = G.Day
and FS.FirstPlace = G.Points
ORDER BY
Margin desc
LIMIT 1