Product Sales Analysis III — LeetCode 1070 Python Solution
MediumDatabase
- Problem
- #1070
- Reading time
- 4 min
- Source
- leetcode.com
Table schema
SQL
Table: Sales +-------------+-------+ | Column Name | Type | +-------------+-------+ | sale_id | int | | product_id | int | | year | int | | quantity | int | | price | int | +-------------+-------+ (sale_id, year) is the primary key (combination of columns with unique values) of this table. Each row records a sale of a product in a given year.Example
SQL
+-------------+-------+
| Column Name | Type |
+-------------+-------+
| sale_id | int |
| product_id | int |
| year | int |
| quantity | int |
| price | int |
+-------------+-------+
(sale_id, year) is the primary key (combination of columns with unique values) of this table.
Each row records a sale of a product in a given year.
A product may have multiple sales entries in the same year.
Note that the per-unit price.Python solution
Python
import duckdb
import pandas as pd
def solution(sales: pd.DataFrame) -> pd.DataFrame:
con = duckdb.connect()
con.register("Sales", sales)
return con.execute("""SELECT
product_id,
year AS first_year,
quantity,
price
FROM Sales
WHERE
(product_id, year) IN (
SELECT
product_id,
MIN(year) AS year
FROM Sales
GROUP BY product_id
);""").df()Complexity
| Measure | Complexity |
|---|---|
| Time | O(n log n) (typical) |
| Space | O(n) auxiliary |
Related problems
Frequently asked questions
- How hard is LeetCode 1070. Product Sales Analysis III?
- LeetCode 1070. Product Sales Analysis III is rated Medium on LeetCode.
- What topics does LeetCode 1070. Product Sales Analysis III cover?
- LeetCode 1070. Product Sales Analysis III is tagged Database on LeetCode.