我有一个包含客户、产品和类别的购买数据集。
customer product category sales_value
A aerosol air_care 10
B aerosol air_care 12
C aerosol air_care 7
A perfume air_care 8
A perfume air_care 2
D perfume air_care 11
C burger food 13
D fries food 6
C fries food 9
对于每种产品,我想要至少购买该产品一次的客户在该产品上花费的销售价值与在该产品类别上花费的销售价值之间的比率。
另一种说法:fries
以至少购买过一次的客户为例,计算 A) 花费在的销售价值fries
的总和和 B) 花费在的销售价值的总和food
。
中间表将采用以下形式:
product category sum_spent_on_product sum_spent_on_category ratio
by_people_buying_product
aerosol air_care 29 39 0.74
perfume air_care 21 31 0.68
burger food 13 22 0.59
fries food 15 28 0.53
示例:人们至少购买aerosol
过一次,在该产品上总共花费了 1800。总体而言,相同的人在该air_care
类别(aerosol
属于)上花费了 3600。因此,比率为aerosol
0.5。
我尝试使用left join lateral
并计算每个给定的中间结果来解决这个问题product
,但我无法理解如何包含条件only for customers who bought this specific product
:
select
distinct (product_id)
, category
, c.sales_category
from transactions t
left join lateral (
select
sum(sales_value) as sales_category
from transactions
where category = t.category
group by category
) c on true
;
上面的查询列出了每个产品在产品类别上的花费总和,但没有所需的产品购买者条件。
是left join lateral
正确的方法吗?普通 SQL 中还有其他解决方案吗?