-
題目:我們想要知道每個顧客在第一段活動期間 (1/1~1/4)、第二段活動期間 (1/5-1/9) 的訂單
-
選取出顧客編號、性別的唯一值,用 DISTINCT 可以從資料庫中把唯一值取出
-
第一段活動期間 (1/1~1/4):CASE WHEN 在這段活動期間,就回傳原欄位中的 orders,不在活動期間就回傳 0,因此所有回傳的 orders 都是在第一段活動期間的,最後再把所以有回傳的 orders 加總
-
第二段活動期間 (1/5~1/9):CASE WHEN 在這段活動期間,就回傳原欄位中的 orders,不在活動期間就回傳 0,因此所有回傳的 orders 都是在第二段活動期間的,最後再把所以有回傳的 orders 加總
SELECT
distinct id
, gender
, SUM(CASE
WHEN grass_date >= date('2022-01-01') and grass_date < date('2022-01-05')
THEN orders
ELSE 0
END) AS first_campaign_gmv
, SUM(CASE
WHEN grass_date >= date('2022-01-05') and grass_date < date('2022-01-10')
THEN orders
ELSE 0
END) AS second_campaign_gmv
FROM customer
group by 1,2
gender
, SUM(first_campaign_gmv) AS first_campaign_gmv
, SUM(second_campaign_gmv) AS second_campaign_gmv
FROM (
SELECT
, gender
, CASE
WHEN grass_date >= date('2022-01-01') and grass_date < date('2022-01-05')
THEN orders
ELSE 0
END AS first_campaign_gmv
, CASE
WHEN grass_date >= date('2022-01-05') and grass_date < date('2022-01-10')
THEN orders
ELSE 0
END AS second_campaign_gmv
FROM customer
group by 1
when orders <= 5 then '<5'
when orders > 5 and orders <= 10 then '5-10'
when orders > 10 and orders <= 15 then '10-15'
when orders > 15 and orders <= 20 then '15-20'
when orders > 20 then '>20' end as orders_tier
, COUNT(distinct id) count_user
FROM (
SELECT
, sum(orders) orders
from customer
group by 1
GROUP BY 1