select
o.category_id,
round(sum(o.order_amount),2) as total_sales,
count(case when c.customer_gender='男' then 1 else null end) as male_customers,
count(case when c.customer_gender='女' then 1 else null end) as female_customers
from
order_details o
left join customer_info c on o.order_id=c.order_id
where
o.order_date between '2024-01-01' and '2024-06-30'
group by
o.category_id
order by
o.category_id asc
这题一开始我写成count(case when c.customer_gender='男' then 1 else 0 end) as male_customers出错,因为0非空,这行也会被统计
要么写成:count(case when c.customer_gender='男' then 1 else null end) as male_customers
要么写成:sum(case when c.customer_gender='男' then 1 else 0 end) as male_customers

京公网安备 11010502036488号