我在DB中有一个表格,如下所示:
ID UserId ProductGender
现在,当用户购买产品时,会在此表中输入有产品的useID和性别。 ProductGender的值可以是Men
,Women
和None
如何计算每位用户购买的男士产品和女士产品的数量。
我已尝试过CASE
和THEN
,但无法找到正确的方法!
答案 0 :(得分:1)
select userid,
sum(productgender = 'Men') as men_sum,
sum(productgender = 'Women') as women_sum,
sum(productgender = 'None') as none_sum,
count(*) - sum(productgender = 'Men') * 100 / count(*) as men_percentage
from your_table
group by userid