我正在尝试创建一个查询,以选择所有最近获得报告最多的用户。我尝试了各种联接,但是我要么获得第一个最大报告,要么如果用户的最大报告早于最后一个报告,则该用户将被忽略。
为清楚起见,这是我正在使用的数据的示例:
id user_id report_id earned
1 20 1 55
2 20 3 30
...
7 20 3 29
8 40 3 50
9 40 3 50
10 20 3 30
11 40 3 35
...
我想为所有用户为给定的report_id选择收入最高的最新报告。对于上面的示例,所需的查询将返回
id user_id report_id earned
9 40 3 50
10 20 3 30
但是,我得到ID为2、8的行时,第一个报告的收入最高。
有关数据的注释:
感谢您提供有关此问题的任何帮助。
编辑: 根据要求,这是我尝试使用的查询(从实际问题转换为此问题,可能是一些语法错误)。老实说,我一直在重写同一查询,所以我没有所有尝试。
SELECT
s.id, s.user_id, s.report_id, s.earned
FROM
submission s
JOIN user u ON s.user_id = u.id
JOIN report r ON s.report_id = r.id
JOIN (SELECT
t.id AS ID, t.user_id, MAX(s.earned) AS MaxReport
FROM submission t
JOIN report r ON t.report_id = r.id
JOIN user us ON t.user_id = us.id
WHERE r.id = 3
GROUP BY t.user_id
ORDER BY ...
) BestReport ON
(s.id = BestReport.ID AND s.user_id = BestReport.user_id AND s.earned = BestReport.MaxReport
WHERE r.id = 3
答案 0 :(得分:0)
我认为您需要这个:
select max(s.id) id, s.user_id, s.report_id, s.earned from (
select user_id, report_id, max(earned) maxearned
from submission
group by user_id, report_id
) g inner join submission s
on s.user_id = g.user_id and s.report_id = g.report_id and s.earned = g.maxearned
group by s.user_id, s.report_id, s.earned
请参见demo
如果只想查询report_id = 3
:
select max(s.id) id, s.user_id, s.report_id, s.earned from (
select user_id, report_id, max(earned) maxearned
from submission
where report_id = 3
group by user_id, report_id
) g inner join submission s
on s.user_id = g.user_id and s.report_id = g.report_id and s.earned = g.maxearned
group by s.user_id, s.report_id, s.earned
order by id
请参见demo
答案 1 :(得分:0)
假设ID越高,则报告越新(存储时间戳会更好),您可以在最新版本的sqlite中使用窗口函数来简化很多事情:
SELECT id, user_id, report_id, earned
FROM (SELECT id, user_id, report_id, earned
, rank() OVER (PARTITION BY report_id, user_id ORDER BY earned DESC, id DESC) AS ranking
FROM example)
WHERE ranking=1 AND report_id=3;
id user_id report_id earned
---------- ---------- ---------- ----------
10 20 3 30
9 40 3 50