我需要找到按月购买巧克力的客户所售出巧克力的百分比。以下面的示例表为例,该表仅包含一个月条目:
Cust_Id Customer Quantity Item Amount in $ Date Month and year
1 Maria 2 chocolate 10 01/01/2020 1-2020
1 Maria 1 banana 5 01/01/2020 1-2020
1 Maria 3 cookies 3 01/01/2020 1-2020
2 Carlos 5 cookies 10 01/01/2020 1-2020
2 Carlos 3 banana 3 01/01/2020 1-2020
3 Jose 1 banana 5 01/01/2020 1-2020
3 Jose 1 chocolate 3 01/01/2020 1-2020
4 Anne 10 chocolate 20 01/01/2020 1-2020
4 Anne 1 banana 5 01/01/2020 1-2020
4 Anne 10 cookies 15 01/01/2020 1-2020
在2020年1月购买巧克力的客户中(玛丽亚,何塞和安妮,但[[否卡洛斯),购买总金额中有多少(以百分比为单位)用于巧克力?
通过Excel中的数据透视表的解决方案:Month 1 2020
Customer Name SUM of Amount in $ Total amount of purchase Overall %
Anne 20 40
Jose 3 8
Maria 10 18
Grand Total 33 66 50.00%
如何确定仅在该日期段内通过SQL购买了巧克力的客户在每个日期段内售出巧克力的百分比?
select customer,
sum(case when item = 'chocolate' then amount end) as chocolate_amount,
sum(amount) as total_amount,
(sum(case when item = 'chocolate' then amount end) /
sum(amount)
) as chocolate_ratio
from t
where date >= '2020-01-01' and date < '2020-02-01'
group by customer
having sum(case when item = 'chocolate' then 1 else 0 end) > 0