sqlite - 给定 ID 的最后一个 MAX 报告值
问题描述
我正在尝试创建一个查询来选择所有获得最后一次最大报告的用户。我尝试了各种连接,但我要么得到第一个最大报告,要么如果用户的最大报告在他们的最后一个报告之前,则忽略用户。
为清楚起见,这是我正在使用的数据的示例:
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
解决方案
我认为你需要这个:
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
如果您只想查询以下内容,请参阅演示: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
查看演示
推荐阅读
- mysql - information_schema 中表行数的差异
- python - 我如何让 Mac 10.13 将模块安装到 3.x 安装而不是 2.7
- sql-server - sql server中的临时表替换
- c# - 在内存中打开 Asp.Net MVC 视图(不在浏览器中)
- javascript - 如何制作html
标签不是在css中添加换行符而是尾随空格?
- c - C/C++ 中的巴特沃斯 BP 滤波,奇怪的频谱
- c - 了解结构内部的结构
- json - json.loads 和 pickle.loads 不能与 async 关键字一起使用?
- python - 使用 pdfminer,代码会卡在命令解释器.process_page(page) 上,并且永远不会终止或抛出错误
- android - 当用户在 RecyclerView + PagerSnapHelper 上卡住滑动时,ScrollListener 代码无法按预期工作