Skip to main content

LeetCode 1070. Product Sales Analysis III SQL Solution

Problem

LeetCode SQL Problem

  1. Product Sales Analysis III

Sales table

sale_idproduct_idyearquantityprice
11002008105000
21002009125000
72002011159000

Product table

product_idproduct_name
100Nokia
200Apple
300Samsung

Solution

Product Sales Analysis III
-- Find the first sale year of every product
WITH ProductFirstYear
AS (
SELECT product_id
,min(year) AS first_year
FROM Sales
GROUP BY product_id
)
-- Select the product id, year, quantity, and price for the first year of every product sold.
SELECT S.product_id
,PFY.first_year
,S.quantity
,S.price
FROM Sales AS S
INNER JOIN ProductFirstYear AS PFY ON S.product_id = PFY.product_id
AND S.year = PFY.first_year

Query Output

product_idfirst_yearquantityprice
1002008105000
2002011159000