这几天新增的题感觉都是这个套路啊,在用户表里加入空值数据

with t as (
select o.customer_id,customer_name,
count(distinct o.order_id) as feb_2024_order_count,
round(sum(qty*price),2) as feb_2024_total_amount,
min(order_date) as feb_2024_first_order_date,
max(order_date) as feb_2024_last_order_date
from orders as o
left join customers as c on o.customer_id = c.customer_id
left join order_items as oi on oi.order_id = o.order_id
where order_date like '2024-02%'
group by o.customer_id
)
select c.customer_id,c.customer_name,
coalesce(feb_2024_order_count,0) as feb_2024_order_count,
coalesce(feb_2024_total_amount,0) as feb_2024_total_amount,
coalesce(round(feb_2024_total_amount/feb_2024_order_count,2),0.00) as feb_2024_avg_order_amount,
feb_2024_first_order_date,feb_2024_last_order_date from customers as c
left join t on t.customer_id = c.customer_id
order by feb_2024_total_amount desc,c.customer_id