1083.case when語句
阿新 • • 發佈:2021-06-27
方法一:case when語句
select buyer_id from ( select buyer_id, case product_name when 'S8' then 0 else 1 end as r from Sales a left join Product b on a.product_id=b.product_id where product_name in ('S8','iPhone') ) c group by c.buyer_id having sum(r)=0;
解題思維:
第一步:將Sales表和Product表進行聯合;
第二步:篩選出product_name是'S8'和'iPhone'的行。我這麼做的目的是使自己不要被無關的東西干擾,思維更加清晰。
第三步:根據題目是要選擇只購買了S8,沒有購買iPhone的買家。比如買家1買了S8(個數不限),買家2買了S8(個數不限)和iPhone(個數不限),買家3買了iPhone(個數不限),怎麼才能只選出買家1呢?這裡需要用到數學思維,買家買S8,記為0,買iPhone記為1,那麼無論買幾個S8合計都為0,只要買iPhone合計就大於0。
方法二:case when語句+sum
select buyer_id from ( select buyer_id, case p.product_name when 'S8' then 1 else 0 end S8, case p.product_name when 'iPhone' then 1 else 0 end iPhone from Sales s left join Product p on s.product_id=p.product_id ) a group by buyer_id having sum(S8)>0 and sum(iPhone)=0;