Average Selling Price — LeetCode 1251 Python Solution
EasyDatabase
- Problem
- #1251
- Reading time
- 3 min
- Source
- leetcode.com
Table schema
SQL
Table: Prices +---------------+---------+ | Column Name | Type | +---------------+---------+ | product_id | int | | start_date | date | | end_date | date | | price | int | +---------------+---------+ (product_id, start_date, end_date) is the primary key (combination of columns with unique values) for this table. Each row of this table indicates the price of the product_id in the period from start_date to end_date.Example
SQL
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| product_id | int |
| start_date | date |
| end_date | date |
| price | int |
+---------------+---------+
(product_id, start_date, end_date) is the primary key (combination of columns with unique values) for this table.
Each row of this table indicates the price of the product_id in the period from start_date to end_date.
For each product_id there will be no two overlapping periods. That means there will be no two intersecting periods for the same product_id.Python solution
Python
import duckdb
import pandas as pd
def solution(prices: pd.DataFrame, units_sold: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Prices", prices)
con.register("UnitsSold", units_sold)
return con.execute("""SELECT
p.product_id,
IFNULL(ROUND(SUM(price * units) / SUM(units), 2), 0) AS average_price
FROM
Prices AS p
LEFT JOIN UnitsSold AS u
ON p.product_id = u.product_id AND purchase_date BETWEEN start_date AND end_date
GROUP BY 1;""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1251. Average Selling Price?
- LeetCode 1251. Average Selling Price is rated Easy on LeetCode.
- What topics does LeetCode 1251. Average Selling Price cover?
- LeetCode 1251. Average Selling Price is tagged Database on LeetCode.