首页 > 解决方案 > 给定 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

标签: sqlite

解决方案


我认为你需要这个:

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

查看演示


推荐阅读