User Product count Percentage
User1 Product1 21 38.1818
User1 Product2 34 61.8182
上面提到的“百分比”是按count / total_count * 100计算的。我有以下代码实现这一点。
select user, product, count(id) as count, count(id)/55*100 from table1 where
user=user1 group by product.
但是数字55已被硬编码。我不希望它被硬编码。因此,我怎样才能实现这一目标。我尽我所知尽力,但确实有效。
答案 0 :(得分:3)
在MySQL中,您将使用join
/相关子查询:
select user, product, count(id) as count,
count(id) / (select count(*) from table1 tt1 where tt1.user = t1.user)
from table1 t1
where t1.user = user1
group by user, product;
在MySQL 8.0+中,您只需使用窗口函数:
select user, product, count(id) as count,
count(id) / sum(count(*)) over (partition by user)
from table1 t1
where t1.user = user1
group by user, product;