EasyNo. 1068

Product Sales Analysis I — LeetCode 1068 Python Solution

Topics
Database
Reading time
2 min

The problem

For every sale, report the name of the product that was sold, the year of the sale and the unit price, 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_name | year | price |
| ------------ | ---- | ----- |
| Router       | 2019 | 1200  |
| Router       | 2020 | 1150  |
| Laptop       | 2020 | 4300  |

Each sale is matched to its product name through product_id, so the two Router sales keep their own year and price and the single Laptop sale follows.

Python solution

PythonSolution
import pandas as pd

def sales_analysis(sales: pd.DataFrame, product: pd.DataFrame) -> pd.DataFrame:
    merged = sales.merge(product, on='product_id')
    return merged[['product_name', 'year', 'price']]

Complexity

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

Related problems

Related problems
No.ProblemDifficulty
0175Combine Two TablesEasy
0176Second Highest SalaryMedium
0177Nth Highest SalaryMedium
0178Rank ScoresMedium
0180Consecutive NumbersMedium
0181Employees Earning More Than Their ManagersEasy

Frequently asked questions

How hard is LeetCode 1068. Product Sales Analysis I?

LeetCode 1068. Product Sales Analysis I is rated Easy on LeetCode.

What topics does LeetCode 1068. Product Sales Analysis I cover?

LeetCode 1068. Product Sales Analysis I 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.