+---------------+---------+
|Column Name |Type|+---------------+---------+
| product_id | int || new_price | int || change_date | date |+---------------+---------+
(product_id, change_date) is the primarykey (combination of columns withuniquevalues) of this table.
Eachrowof this table indicates that the price ofsome product was changed to a new price atsome date.
Write a solution to find the prices of all products on 2019-08-16. Assume the price of all products before any change is 10.
We need to find the price of each product as of a specific date. For each product, find the latest price change on or before the given date; if none, the price is 10.
SELECT p.product_id, COALESCE(t.new_price, 10) AS price
FROM (SELECTDISTINCT product_id FROM Products) p
LEFTJOIN (
SELECT product_id, new_price
FROM Products
WHERE (product_id, change_date) IN (
SELECT product_id, MAX(change_date)
FROM Products
WHERE change_date <='2019-08-16'GROUPBY product_id
)
) t ON p.product_id = t.product_id;
1
2
3
4
5
6
7
8
9
10
11
12
SELECT p.product_id, COALESCE(t.new_price, 10) AS price
FROM (SELECTDISTINCT product_id FROM Products) p
LEFTJOIN (
SELECT product_id, new_price
FROM Products
WHERE (product_id, change_date) IN (
SELECT product_id, MAX(change_date)
FROM Products
WHERE change_date <='2019-08-16'GROUPBY product_id
)
) t ON p.product_id = t.product_id;
1
2
3
4
5
6
7
8
9
10
11
12
13
# Assume Products is a pandas DataFrameimport pandas as pd
defproduct_price_at_given_date(Products: pd.DataFrame) -> pd.DataFrame:
Products = Products.copy()
Products['change_date'] = pd.to_datetime(Products['change_date'])
asof_date = pd.to_datetime('2019-08-16')
# Find latest change on or before the date mask = Products['change_date'] <= asof_date
latest = Products[mask].sort_values(['product_id', 'change_date']).groupby('product_id').last().reset_index()
all_ids = Products[['product_id']].drop_duplicates()
result = all_ids.merge(latest[['product_id', 'new_price']], on='product_id', how='left')
result['price'] = result['new_price'].fillna(10).astype(int)
return result[['product_id', 'price']]