union all 同一张表 优化语句

select delivery_phone
from (
  select delivery_phone, '1' as c_week
  from wm_order_line
  where paid_date >= '2019-10-18' and paid_date <= '2019-10-24' 
  and store_id in ('2800','2801','2803','2804','2805','2806','2807','2808') --super
  group by delivery_phone 
union all
  select delivery_phone, '2' as c_week
  from wm_order_line
  where paid_date >= '2019-10-25' and paid_date <= '2019-10-31' 
  and store_id in ('2800','2801','2803','2804','2805','2806','2807','2808') 
  group by delivery_phone 
union all
  select delivery_phone, '3' as c_week
  from wm_order_line
  where paid_date >= '2019-11-01' and paid_date <= '2019-11-07' 
  and store_id in ('2800','2801','2803','2804','2805','2806','2807','2808') 
  group by delivery_phone 
) as t
group by t.delivery_phone
having count(distinct t.c_week) = 3
order by delivery_phone

 

优化,只读一次表

SELECT delivery_phone
from (
SELECT 
 delivery_phone,
 case 
   when paid_date >= '2019-10-18' and paid_date <= '2019-10-24' then '1'
   when paid_date >= '2019-10-25' and paid_date <= '2019-10-31' then '2'
   when paid_date >= '2019-11-01' and paid_date <= '2019-11-07' then '3'
 end as c_week
from wm_order_line
where paid_date >= '2019-10-18' and paid_date <= '2019-11-07' 
and store_id in ('2800','2801','2803','2804','2805','2806','2807','2808') 
) a 
group by delivery_phone
having count(distinct c_week) = 3
order by delivery_phone

 

posted @ 2020-04-13 23:59  茗::流  阅读(1450)  评论(0)    收藏  举报
如有雷同,纯属参考。如有侵犯你的版权,请联系我。