Skip to content
Advertisement

Select data using closest date

I have two tables like below:

table1

table2

I have to calculate TotalPrice (price x Quantity) from each ID for the date ‘2017-07-28’ but condition is that: if no price is available for a given date, the price closest to but before the date should be used.

I have tried the below query but its not giving the proper output.

For calculation of ‘C’ price of 2014-07-27 should be taken.

Advertisement

Answer

Just use a sub-query to obtain the relevant price and then multiply:

This returns:

AsOfDate ID TotalPrice
2017-01-31 A 17452.00
2017-02-28 A 35964.00
2017-02-01 B 9960.00
2017-02-28 B 14735.00
2017-01-31 C 78910.00
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement