我有一个名为service_t的表,它有一列effective_dt,其中填充了unix时间戳。我需要找到max effective_dt的所有行,但effective_dt必须小于给定值。我有以下sql,但我认为它没有效率:
Select *
from service_t t1
where t1.effective_dt <= :given_value
and t1.effective_dt = (select max(effective_dt)
from service_t t2
where t2.effective_dt <= :given_value
and t1.id = t2.id)
这种效率还是其他好方法?谢谢!
答案 0 :(得分:2)
使用分析函数可能更有效:
Select * from (
select t1.*,
dense_rank() over (partition by id order by effective_dt desc) rn
from service_t t1
where t1.effective_dt <= :given_value)
where rn = 1