MediumNo. 1070

Product Sales Analysis III — LeetCode 1070 Python Solution

Topics
Database
Reading time
4 min

Table schema

SQLTable schema
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

SQLExample
+-------------+-------+
| 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

PythonSolution
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

Time
O(n log n)(typical)
Space · auxiliary
O(n)

Related problems

Related problems
No.ProblemDifficulty
1068Product Sales Analysis IEasy
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.