0

I want to join two tables. Tables are following below,

Table A:

Batch_ID INT,
Start_Dt DATE,
Expiry_Dt DATE

Table B:

Purchase_Dt DATE

I need to get two oldest batch code for each purchase date. Purchase date should be greater than or equal to start_dt and expiry_dt should be less than or equal to purchase date.

Fahmi
  • 37,315
  • 5
  • 22
  • 31

1 Answers1

1

You can try using row_number()

select Purchase_Dt,Batch_ID from
(
select Purchase_Dt,Batch_ID,row_number() over(partition by Purchase_Dt order by batch_id desc) as rn 
from B join A on Purchase_Dt>=start_dt and Purchase_Dt<=Expiry_Dt
)f where rn=1
Fahmi
  • 37,315
  • 5
  • 22
  • 31