SQL计算类别重叠百分比时同类结果非100%问题排查
问题原因
你的代码计算占比时使用的分母count(*)是自连接后生成的总记录条数,并非当前行类别对应的独立item总数。因为单个item可能同时归属多个类别,自连接后会生成多条重复记录,导致分母远大于类别实际的item数量,所以出现同类别重叠占比不足100%的问题。同时你原代码中join条件的字段名和表结构不匹配,原表字段为item_id而非item。
修正代码
select t.category_name, concat(round(countif( t2.category_name = 'category1' ) * 100 / count(DISTINCT t.item_id), 2), '%') as category1, concat(round(countif( t2.category_name = 'category2' ) * 100 / count(DISTINCT t.item_id), 2), '%') as category2, concat(round(countif( t2.category_name = 'category3' ) * 100 / count(DISTINCT t.item_id), 2), '%') as category3, concat(round(countif( t2.category_name = 'category4' ) * 100 / count(DISTINCT t.item_id), 2), '%') as category4, concat(round(countif( t2.category_name = 'category5' ) * 100 / count(DISTINCT t.item_id), 2), '%') as category5, concat(round(countif( t2.category_name = 'category6' ) * 100 / count(DISTINCT t.item_id), 2), '%') as category6 from t join t t2 on t.item_id = t2.item_id group by t.category_name;
逻辑说明
- 用
count(DISTINCT t.item_id)统计当前行类别关联的总item数,作为占比计算的分母,保证同类别占比为100% - 补充category6的统计列,匹配你预期的输出结构
- 用
round()保留两位小数,用concat()拼接百分号,直接生成符合要求的百分比格式输出
内容的提问来源于stack exchange,提问作者user16228179
相关产品推荐
相关产品推荐

