0

I have a table called service_t,it has a column effective_dt which is populated with unix timestamp. I need find all rows with max effective_dt but the effective_dt must be less than a given value. I have the following sql but I don’t think it’s efficient:

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)

Is this efficient or any other good ways? Thanks!

2
  • Do you mean efficient in terms of performance or just a better way to code this? Commented Oct 5, 2012 at 14:19
  • in terms performance and abetter way to code it, thanks! Commented Oct 5, 2012 at 14:28

1 Answer 1

2

Using analytic functions is probably more efficient:

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.