azarasi / LeetCode 1084. Sales Analysis III

Created Wed, 13 Apr 2022 17:42:35 +0800 Modified Wed, 18 Sep 2024 14:00:22 +0000

Table: Product

Column NameType
product_idint
product_namevarchar
unit_priceint

product_id is the primary key of this table. Each row of this table indicates the name and the price of each product.

Table: Sales

Column NameType
seller_idint
product_idint
buyer_idint
sale_datedate
quantityint
priceint

This table has no primary key, it can have repeated rows. product_id is a foreign key to the Product table. Each row of this table contains some information about one sale.

Write an SQL query that reports the products that were only sold in the spring of 2019. That is, between 2019-01-01 and 2019-03-31 inclusive.

Return the result table in any order.

The query result format is in the following example.

Example 1:

Input: Product table:

product_idproduct_nameunit_price
1S81000
2G4800
3iPhone1400

Sales table:

seller_idproduct_idbuyer_idsale_datequantityprice
1112019-01-2122000
1222019-02-171800
2232019-06-021800
3342019-05-1322800

Output:

product_idproduct_name
1S8

Explanation: The product with id 1 was only sold in the spring of 2019. The product with id 2 was sold in the spring of 2019 but was also sold after the spring of 2019. The product with id 3 was sold after spring 2019. We return only product 1 as it is the product that was only sold in the spring of 2019.

Solution

SELECT s.product_id,
       p.product_name
FROM Sales s
         LEFT JOIN Product p ON s.product_id = p.product_id
GROUP BY s.product_id
HAVING MIN(sale_date) >= '2019-01-01'
   AND MAX(sale_date) <= '2019-03-31';