题目
表结构
数据
结果
解答:
1.连接表,查看按日期顺序卖出的产品都有哪些
select orders.seller_id,
orders.order_date,
orders.item_id,
items.item_id item_ids,
item_brand,row_number() over(partition by seller_id order by order_date) as rk
from Orders
join Items
on Orders.item_id=Items.item_id
1.1 看第二件
select *
from(
select orders.seller_id,
orders.order_date,
orders.item_id,
items.item_id item_ids,
item_brand,row_number() over(partition by seller_id order by order_date) as rk
from Orders
join Items
on Orders.item_id=Items.item_id
) a
where rk=2
2.查item_brand和卖家最爱的favorite_brand 是否相同
select * ,
case when item_brand = favorite_brand then 'yes' # 第一种方法,使用case when then else end
else 'no' end 'love' ,
if(favorite_brand=item_brand ,'yes','no') # 第二种方法,使用if函数
from users,items
3.连接1.2表结果
select Users.user_id as seller_id,
if(favorite_brand=item_brand,'yes','no') as 2nd_item_fav_brand ,
case when item_brand=favorite_brand then 'yes'
else 'no' end '2nd_item_fav_brands'
from Users
left join
(
select *
from(
select orders.seller_id,
orders.order_date,
orders.item_id,
items.item_id item_ids,
item_brand,row_number() over(partition by seller_id order by order_date) as rk
from Orders
join Items
on Orders.item_id=Items.item_id
) a
where rk=2
) b
on Users.user_id =b.seller_id