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

Latest price as of each order

Medium·Acceptance ·Asked 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

Example

order_id product_id ordered_at price 1 55 2024-02-10 12:00 19.99 2 55 2024-03-05 08:30 24.50

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

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.