SQL同一個欄位出現null和0值,有何區別,原因是什麼?left join導致null值出現,case when導致0值出現
阿新 • • 發佈:2021-12-02
-- create table visit_hist( -- customer_id int comment '客戶id' -- ,visit_date int comment '訪問日期' -- ) -- delete from visit_hist; -- insert into visit_hist(customer_id,visit_date) values -- (11,11),(11,7),(22,5),(66,8),(55,4),(11,35),(22,32),(33,31),(55,39) -- with t1 as ( -- select customer_id -- ,visit_date-- from visit_hist vh -- where visit_date <30 -- ) -- 每個客戶觀察日(第30日)之前的最大拜訪日期 with t2 as ( select customer_id ,max(visit_date) as max_visit_date from visit_hist vh where visit_date <30 group by customer_id )
-- select * from t2
-- 每個客戶在觀察日之前的最晚一個拜訪日期之後30天內的拜訪次數 ,t3 as (select t2.customer_id ,t2.max_visit_date ,sum(case when t_all.visit_date<t2.max_visit_date+30 then 1 else 0 end) as total_cnt_after from t2 left join visit_hist t_all on t2.customer_id=t_all.customer_id where t_all.visit_date >=30 and t_all.visit_date <90 group by t2.customer_id ) -- 這一句會產生total_cnt_after等於0的行,主要是由case when判斷產生 -- select* from t3;
-- 下面的left join由於主表是t2其中的customer_id比t3多,因此會導致t2的某些行total_cnt_after為null值 -- -- 對觀察日之前有過拜訪記錄的客戶打上標籤 -- select t2.customer_id -- ,t3.total_cnt_after -- ,case when t3.total_cnt_after>0 then 1 else 0 end as is_active -- from t2 -- left join t3 on t2.customer_id=t3.customer_id;
-- 列印MySQL版本 -- select version();