Calculate Product Final Price - Problem
You're building a smart pricing system for an e-commerce platform! ๐
Given two database tables - Products and Discounts - you need to calculate the final price of each product after applying category-based discounts.
Your mission:
- ๐ Join products with their category discounts
- ๐ฐ Calculate final price = original price - (discount% ร original price)
- ๐ท๏ธ Handle products with no discounts (price remains unchanged)
- ๐ Return results ordered by product_id
Tables Structure:
Products: Contains product_id (unique), category, and original priceDiscounts: Contains category (primary key) and discount percentage (0-100)
Think of it like a smart cashier that automatically applies the right discount based on what category each item belongs to!
Input & Output
example_1.sql โ Basic Scenario
$
Input:
Products: [(1,'Electronics',1000), (2,'Clothing',50), (3,'Electronics',1200), (4,'Home',500)]
Discounts: [('Electronics',10), ('Clothing',20)]
โบ
Output:
[(1,900,'Electronics'), (2,40,'Clothing'), (3,1080,'Electronics'), (4,500,'Home')]
๐ก Note:
Electronics gets 10% off (1000โ900, 1200โ1080), Clothing gets 20% off (50โ40), Home has no discount (500โ500)
example_2.sql โ No Discounts Available
$
Input:
Products: [(1,'Books',25), (2,'Sports',100)]
Discounts: []
โบ
Output:
[(1,25,'Books'), (2,100,'Sports')]
๐ก Note:
When no discounts exist, all products retain their original prices
example_3.sql โ All Products Have Discounts
$
Input:
Products: [(1,'Electronics',2000), (2,'Clothing',80)]
Discounts: [('Electronics',25), ('Clothing',15)]
โบ
Output:
[(1,1500,'Electronics'), (2,68,'Clothing')]
๐ก Note:
All categories have matching discounts: Electronics 25% off (2000โ1500), Clothing 15% off (80โ68)
Constraints
- 1 โค number of products โค 104
- 0 โค number of discount categories โค 100
- 1 โค product_id โค 106
- 1 โค price โค 106
- 0 โค discount โค 100 (percentage)
- Category names are non-empty strings with max length 50
- Each product_id is unique
- Each discount category appears at most once
Visualization
Tap to expand
Understanding the Visualization
1
Customer's Cart
Products from different categories arrive at checkout
2
Discount Lookup
System checks if each category has an active discount
3
Price Calculation
Applies discount percentage to original price
4
Final Receipt
Shows final prices ordered by product ID
Key Takeaway
๐ฏ Key Insight: LEFT JOIN is perfect for optional relationships - every product gets processed, but discounts are applied only when available!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code