美文网首页
销量最高,group by分组筛选

销量最高,group by分组筛选

作者: 笃见弥月 | 来源:发表于2021-12-09 19:29 被阅读0次

    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
    

    相关文章

      网友评论

          本文标题:销量最高,group by分组筛选

          本文链接:https://www.haomeiwen.com/subject/egaffrtx.html