create table fruit (
idx int primary key auto_increment,
goods_id int,
farm_id int
);
create table orders (
idx int primary key auto_increment,
order_id int,
goods_id int,
farm_id int
);
insert into fruit (goods_id, farm_id) values
(1,2),
(1,3),
(2,2);
insert into orders (order_id, goods_id, farm_id) values
(1,1,2),
(2,2,2);
Input:
Users table:
+---------+------------+----------------+
| user_id | join_date | favorite_brand |
+---------+------------+----------------+
| 1 | 2019-01-01 | Lenovo |
| 2 | 2019-02-09 | Samsung |
| 3 | 2019-01-19 | LG |
| 4 | 2019-05-21 | HP |
+---------+------------+----------------+
Orders table:
+----------+------------+---------+----------+-----------+
| order_id | order_date | item_id | buyer_id | seller_id |
+----------+------------+---------+----------+-----------+
| 1 | 2019-08-01 | 4 | 1 | 2 |
| 2 | 2019-08-02 | 2 | 1 | 3 |
| 3 | 2019-08-03 | 3 | 2 | 3 |
| 4 | 2019-08-04 | 1 | 4 | 2 |
| 5 | 2019-08-04 | 1 | 3 | 4 |
| 6 | 2019-08-05 | 2 | 2 | 4 |
+----------+------------+---------+----------+-----------+
Items table:
+---------+------------+
| item_id | item_brand |
+---------+------------+
| 1 | Samsung |
| 2 | Lenovo |
| 3 | LG |
| 4 | HP |
+---------+------------+
Output:
+-----------+--------------------+
| seller_id | 2nd_item_fav_brand |
+-----------+--------------------+
| 1 | no |
| 2 | yes |
| 3 | yes |
| 4 | no |
+-----------+--------------------+
Explanation:
The answer for the user with id 1 is no because they sold nothing.
The answer for the users with id 2 and 3 is yes because the brands of their second sold items are their favorite brands.
The answer for the user with id 4 is no because the brand of their second sold item is not their favorite brand.
-- 1) 유일함을 보장하는 것 : 판매자가 두 번째로 판매한 상품, 두 번 이상 판매한 적이 없는 판매자의 목록
-- 2) 유일함을 보장하지 않는 것 : 선호 상품
-- 1)과 2)를 join 하면 뻥튀기가 발생할 수 있음
-- 모든 유저를 두 번째를 판매한 유저와 하지 아니한 유저를 분류한다.
-- 판매한 유저의 경우 판매한 상품과 선호상품의 일치여부를 비교한다.
with fav as(
select
u.user_id
, i.item_id
from users u
join items i
on u.favorite_brand = i.item_brand
)
, 2ndOrd as(
select
seller_id
, item_id
from (
select
seller_id
, item_id
, row_number() over (partition by seller_id order by order_date asc) ranks
from orders
)tb
where ranks = 2
)
select
u.user_id seller_id
, case when tb.isPresent is not null then 'yes'
else 'no'
end '2nd_item_fav_brand'
from users u
left join (
select
user_id
, 'yes' isPresent
from 2ndOrd s
join fav f
on s.seller_id = f.user_id and s.item_id = f.item_id
) tb
on u.user_id = tb.user_id