Sales Analysis II LeetCode Solution

Last updated on January 21st, 2025 at 09:56 pm

Here, we see the Sales Analysis II LeetCode Solution. This Leetcode problem is solved using MySQL and Pandas.

List of all LeetCode Solution

Level of Question

Easy

Sales Analysis II LeetCode Solution

Sales Analysis II LeetCode Solution

1. Problem Statement

Column NameType
product_idint
product_namevarchar
unit_priceint
Table: Product

product_id is the primary key (column with unique values) of this table. Each row of this table indicates the name and the price of each product.

Column NameType
seller_idint
product_idint
buyer_idint
sale_datedate
quantityint
priceint
Table: Sales

This table can have duplicate rows. product_id is a foreign key (reference column) to the Product table. Each row of this table contains some information about one sale.

Write an SQL query that reports the buyers who have bought S8 but not iPhone. Note that S8 and iPhone are products present in the Product table.

The result format is in the following example.

product_idproduct_nameunit_price
1S81000
2G4800
3iPhone1400
Product table:
seller_idproduct_idbuyer_id sale_datequantityprice
1112019-01-2122000
1222019-02-171800
2232019-06-021800
3342019-05-1322800
Sales table:
Output:
buyer_id
1

Explanation:
The buyer with id 1 bought an S8 but didn’t buy an iPhone. The buyer with id 3 bought both.

2. Code Implementation in Different Languages

2.1 Sales Analysis II MySQL

select 
  distinct s.buyer_id 
from 
  Sales as s 
  join Product as p on s.product_id = p.product_id 
where 
  product_name = 'S8' 
  and s.buyer_id not in (
    select 
      buyer_id 
    from 
      Sales as s 
      join Product as p on s.product_id = p.product_id 
    where 
      product_name = 'iPhone'
  );

2.2 Sales Analysis II MySQL (Another approach)

select 
  buyer_id 
from 
  Sales 
  join Product using(product_id) 
group by 
  buyer_id 
having 
  sum(product_name = 'S8') > 0 
  and sum(product_name = 'iPhone') = 0;
Scroll to Top