根据条件优化SQL查询以获取今天和前一个工作日的记录

问题描述 投票:0回答:1

我正在编写一个查询,以根据传递的日期和很少的条件来获取记录。我的查询工作正常。我正在寻找优化此查询的方法。

select q.* ,RANK() OVER(partition by q.passengr_id order by q.busndate desc) as myrank from (
    select t1.* from Tracker t1 where t1.busndate='23-APR-20' and t1.psn_status not in (100,101)
    Union all
    select t2.* from Tracker t2 where t2.busndate='22-APR-20' and t2.psn_status  in (100,101)
) q

这里是我从同一张表中获取数据,并用psgnr_id对其进行分组。

唯一的条件是,对于状态100和101,我需要获取上一个工作日的数据。我有两个输入日期。

需要以更好的方式做到这一点的建议。

java mysql sql oracle oracle-sqldeveloper
1个回答
0
投票

您为什么使用union all?为什么不呢?

select t.*, rank() over (partition by q.passengr_id order by q.busndate desc) as myrank
from Tracker t
where (t.busndate = date '2020-04-23' and t1.psn_status not in (100, 101)) or
      (t.busndate = date '2020-04-22' and t1.psn_status in (100, 101))

我不确定这会对性能产生什么影响。但是它应该比您的版本快一点。

© www.soinside.com 2019 - 2024. All rights reserved.