EasyNo. 1069LeetCode Premium

Product Sales Analysis II — LeetCode 1069 Python Solution

Topics
Database
Reading time
2 min

The problem

For every product, report its id and the total quantity sold across all years, in any order. The Sales table has one row per sale: sale_id (int), product_id (int), year (int), quantity (int) and price (int, the price per unit), with the pair (sale_id, year) as the primary key. The Product table maps product_id (int, the primary key) to product_name (varchar).

Example

Example
Sales table:

| sale_id | product_id | year | quantity | price |
| ------- | ---------- | ---- | -------- | ----- |
| 11      | 300        | 2019 | 25       | 1200  |
| 12      | 300        | 2020 | 30       | 1150  |
| 13      | 400        | 2020 | 8        | 4300  |

Product table:

| product_id | product_name |
| ---------- | ------------ |
| 300        | Router       |
| 400        | Laptop       |

Result:

| product_id | total_quantity |
| ---------- | -------------- |
| 300        | 55             |
| 400        | 8              |

Product 300 sold 25 units in 2019 and 30 in 2020 for a total of 55, and product 400 sold 8 units in a single year.

Python solution

PythonSolution
import pandas as pd

def sales_analysis(sales: pd.DataFrame, product: pd.DataFrame) -> pd.DataFrame:
    res = sales.groupby('product_id', as_index=False)['quantity'].sum()
    res.columns = ['product_id', 'total_quantity']
    return res

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 1069. Product Sales Analysis II?

LeetCode 1069. Product Sales Analysis II is rated Easy on LeetCode.

What topics does LeetCode 1069. Product Sales Analysis II cover?

LeetCode 1069. Product Sales Analysis II is tagged Database on LeetCode.

Is LeetCode 1069. Product Sales Analysis II a premium problem?

Yes. LeetCode 1069. Product Sales Analysis II is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

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.