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

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM