Skip to content
Advertisement

Trying to join two tables together to have the unit_price vary based on the day

I have some code drafted but I’m not sure how to finish it, or if it needs more work. It looks like this.

Everything looks good, but how do I get the price to be based on the given effective date? The given effective date is 01/01/2021. I was thinking something maybe like this for the where:

I’m not sure if this is correct though. I tried running it and similar where statements but nothing came of it.

Sample data:

products

product_price

I want the product’s price to now be a calculation based on a given date, using a join between Products and Product_Price.

[This is what the tables look like

Advertisement

Answer

When price data is stored with only a single date, it typically means “use this price from this date onward, but only up to the next date_effective”.

The window function row_number() assigns an integer to each row, within a related over clause, partition by controls what is used to re-start numbering at 1 and an order by determines the sequence of rows and numbers within the partition. So by using a descending date order the most recent date per partition can be identified with a row number of 1.

If you couple this technique with a filter on the effective date being less than or equal to a given date, then the price that applies on the given date will be returned.:

The second join condition could be used as a where condition instead

Sample Data

Results

see this working demo at http://sqlfiddle.com/#!4/8a6c9/2

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement