销量最高,group by分组筛选

LeetCode 1082/1083/1084


image.png

1、查询总销售量price最高的销售者seller_id(有并列)

分组+按sum(price)排序+取最高
① ≥ALL(子查询)

select seller_id
from sales 
group by seller_id
having sum(price)>=all (
      select sum(price)
      from sales
      group by seller_id
    )

② 窗口函数

select seller_id
from (
    select seller_id, dense_rank() over(order by sum(price) desc) rk
    from sales 
    group by seller_id
) t
where t.rk=1

2、购买了S8,但没有购买iPhone的客户

(购买S8数量可能不止1)
先对buyer_id分组,再考虑满足上面的条件

select s.buyer_id
from sales s
left join  product p
on s.product_id=p.product_id
group by buyer_id
having sum(p.product_name='S8')>0 
and sum(p.product_name='iPhone')=0

3、仅在2019-01-01至2019-03-31(含)之间出售的商品

先对product_id分组,找出最大sale_date<'2019-03-31',且最小sale_date>'2019-01-01'的product_id

select p.product_id, p.product_name
from sales s 
left join product p
on s.product_id=p.product_id
group by product_id
having '2019-01-01' <= min(s1.sale_date) 
and max(s1.sale_date) <= '2019-03-31'

或者找出在规定时间外销售量都为0的product_id(以sales表的左外连接,如果一款产品一直没销售出去,不会出现在sales表中)

select p.product_id, p.product_name
from sales s 
left join product p
on s.product_id=p.product_id
group by product_id
having sum(s.sale_date>'2019-03-31')=0
and sum(s.sale_date<'2019-01-01')=0
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容