首页 > 解决方案 > Oracle 优化 SQL 查询 - Multiple Max()

问题描述

我有一个表,首先我需要选择数据,max(event_date)然后需要过滤数据,max(event_sequence)然后再次过滤max(event_number)

我写了以下查询,该查询有效但需要时间。

这里是查询

SELECT DISTINCT a.stuid,
                   a.prog,
                   a.stu_prog_id,
                   a.event_number,
                   a.event_date,
                   a.event_sequence,
                   a.prog_status
   FROM table1 a
   WHERE a.event_date=
       (SELECT max(b.event_date)
        FROM table1 b
        WHERE a.stuid=b.stuid
          AND a.prog=b.prog
          AND a.stu_prog_id=b.stu_prog_id)
     AND a.event_seq=
       (SELECT max(b.event_sequence)
        FROM table1 b
        WHERE a.stuid=b.stuid
          AND a.prog=b.prog
          AND a.stu_prog_id=b.stu_prog_id
          AND a.event_date=b.event_date)
     AND a.event_number=
       (SELECT max(b.event_number)
        FROM table1 b
        WHERE a.stuid=b.stuid
          AND a.prog=b.prog
          AND a.stu_prog_id=b.stu_prog_id
          AND a.event_date=b.event_date
          AND a.event_sequence=b.event_sequence

我想知道有没有更快的方法来获取数据?我正在使用 Oracle 12c。

标签: sqloracleoracle12c

解决方案


您可以尝试使用分析函数重新表述您的查询:

SELECT
    stuid,
    prog,
    stu_prog_id,
    event_number,
    event_date,
    event_sequence,
    prog_status
FROM
(
    SELECT t.*,
        RANK() OVER (PARTITION BY studio, prog, stu_prog_id
                     ORDER BY event_date DESC) rnk1,
        RANK() OVER (PARTITION BY studio, prog, stu_prog_id, event_date
                     ORDER BY event_sequence DESC) rnk2,
        RANK() OVER (PARTITION BY studio, prog, stu_prog_id, event_date, event_sequence
                     ORDER BY event_number DESC) rnk3
    FROM table1 t
) t
WHERE rnk1 = 1 AND rnk2 = 1 AND rnk3 = 1;

注意:我实际上不知道您是否真的需要所有三个子查询。在您的问题中添加示例数据可能会帮助其他人改进我上面给出的解决方案。


推荐阅读