Interview Questions/SQL/Product Sales Summary per Category per Year

Product Sales Summary per Category per Year

Preview mode. Log in to edit, run, submit, and save progress.

Medium

Description

You are given a table of orders. Each order has a product name, a category, a quantity sold, a unit price, and an order date. Write a SQL query to find for each year and category: the number of orders, the total units sold, and the total revenue (quantity × unit_price). Return the result ordered by year and category. Table: Orders

Column NameTypeDescription
idINTPrimary key
product_nameVARCHARName of the product
categoryVARCHARProduct category
quantityINTUnits sold in this order
unit_priceINTPrice per unit
order_dateDATEDate the order was placed

Database Schema (Inferred)

Orders

Column NameExample Value
id1
product_nameLaptop
categoryElectronics
quantity2
unit_price800
order_date2022-03-15

Example

Orders

idproduct_namecategoryquantityunit_priceorder_date
1LaptopElectronics28002022-03-15
2PhoneElectronics54002022-07-20
3DeskFurniture32002022-03-10
4ChairFurniture41502023-01-05
5LaptopElectronics18002023-05-18
6LampFurniture2502023-08-22

Output

yearcategoryorder_counttotal_units_soldtotal_revenue
2022Electronics273600
2022Furniture13600
2023Electronics11800
2023Furniture26700

Explanation:

Group by year (extracted from order_date) and category. Count orders, sum quantities, and sum quantity*unit_price as revenue.

Approach hint

Start with a simple approach, explain the trade-off, then move toward a cleaner or more scalable solution.

Common mistake

Skipping assumptions, edge cases, or trade-offs can make an otherwise good answer feel incomplete.

SQL Editor
Loading...

Orders

idproduct_namecategoryquantityunit_priceorder_date
1LaptopElectronics28002022-03-15
2PhoneElectronics54002022-07-20
3DeskFurniture32002022-03-10
4ChairFurniture41502023-01-05
5LaptopElectronics18002023-05-18
6LampFurniture2502023-08-22

Output

yearcategoryorder_counttotal_units_soldtotal_revenue
2022Electronics273600
2022Furniture13600
2023Electronics11800
2023Furniture26700