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