sql - 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。
解决方案
您可以尝试使用分析函数重新表述您的查询:
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;
注意:我实际上不知道您是否真的需要所有三个子查询。在您的问题中添加示例数据可能会帮助其他人改进我上面给出的解决方案。
推荐阅读
- r - R数据框中的列名可以为空吗?
- javascript - 如何在功能打字稿类中导出方法?
- python-3.x - 蟒蛇 3 | 如何检查数字的前2位是否为00?
- android - 如何为自定义的、不存在的语言创建 android 翻译文件?
- python - 如何防止 Django 使用 managed=False 重命名模型中的键列?
- javascript - 我应该调用 chrome.storage.sync.set 异步吗?
- c - 如何计算包含旋转图像的矩形的大小(可能带有透明像素)
- google-cloud-functions - 无法在网络模拟器上测试谷歌助手操作(错误云功能部署失败。关闭)
- flutter - 颤振:光滑的圆角
- vhdl - 如何在 VHDL 中为 std_logic_vector 赋值?