← Problems20. Latest price as of each orderMediumSQL
00:00 / 20:00

Latest price as of each order

Medium20% solve itAsked at Amazon, Flipkart

Prices change over time and orders must be valued at the price in effect when they were placed. Return each order with the price that was current at ordered_at.

Input schema

orders price_history order_id bigint product_id bigint product_id bigint price numeric ordered_at timestamp valid_from timestamp

Constraints

  • Use the row with the greatest valid_from that is not after ordered_at
  • Orders placed before any price row return null
  • Ties on valid_from take the higher price
  • Order by order_id

Example 1each order takes the price in effect

Input · orders
order_idordered_atproduct_id
12024-02-10 12:00:0055
22024-03-05 08:30:0055
Input · price_history
priceproduct_idvalid_from
19.99552024-01-01 00:00:00
24.5552024-03-01 00:00:00
Output
order_idproduct_idordered_atprice
1552024-02-10 12:00:0019.99
2552024-03-05 08:30:0024.5

Example 2prices are per product

Input · orders
order_idordered_atproduct_id
12024-04-01 00:00:0010
22024-04-01 00:00:0020
Input · price_history
priceproduct_idvalid_from
5102024-01-01 00:00:00
8202024-01-01 00:00:00
Output
order_idproduct_idordered_atprice
1102024-04-01 00:00:005
2202024-04-01 00:00:008

Topics

data modelingjoins

Similar problems

Community-reported interview topic. Not an official company question and no affiliation is implied.

solution.sql
Loading editor…
Draft not saved yet · Spaces 4 · UTF-8⌘↵ run ⌘⇧↵ submit
Nothing run yet

Run against the public tests, or submit to score against all of them.