Skip to content

Latest commit

 

History

History
73 lines (48 loc) · 2.3 KB

File metadata and controls

73 lines (48 loc) · 2.3 KB

Question 1068: Product Sales Analysis I

LeetCode URL: https://leetcode.com/problems/product-sales-analysis-i/

Description

Write a solution to report the product_name, year, and price for each sale_id in the Sales table. Return the resulting table in any order. The result format is in the following example.

Table Schema Structure

Create table If Not Exists Sales (sale_id int, product_id int, year int, quantity int, price int);
Create table If Not Exists Product (product_id int, product_name varchar(10));

Sample Input Data

insert into Sales (sale_id, product_id, year, quantity, price) values ('1', '100', '2008', '10', '5000');
insert into Sales (sale_id, product_id, year, quantity, price) values ('2', '100', '2009', '12', '5000');
insert into Sales (sale_id, product_id, year, quantity, price) values ('7', '200', '2011', '15', '9000');
insert into Product (product_id, product_name) values ('100', 'Nokia');
insert into Product (product_id, product_name) values ('200', 'Apple');
insert into Product (product_id, product_name) values ('300', 'Samsung');

Expected Output Data

+--------------+-------+-------+
| product_name | year  | price |
+--------------+-------+-------+
| Nokia        | 2008  | 5000  |
| Nokia        | 2009  | 5000  |
| Apple        | 2011  | 9000  |
+--------------+-------+-------+

SQL Solution

SELECT p.product_name,s.year,s.price
FROM sales_1068 s
JOIN product_1068 p ON s.product_id = p.product_id;

Solution Breakdown

Goal

The query builds the final result columns product_name, year, price from sales, product.

Result Grain

Row grain follows the post-filter join output.

Step-by-Step Logic

  1. Combine datasets using JOIN. Join predicates control row matching and prevent accidental cartesian growth.
  2. Project final output columns: product_name, year, price.

Why This Works

Join conditions align related entities so each output row is built from the correct source records. The final projection exposes only the columns required by the result contract.

Performance Notes

Primary cost drivers are join operations. Indexes on join/filter/group keys typically provide the biggest speedup.

Common Pitfalls

  • Verify join keys and cardinality; wrong joins can duplicate or drop rows silently.