You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在SQL中创建占比列?基于分组数据计算ID占比

如何新增rate列计算ID数量占比?

原查询语句

select 
company_type, year_month, months_since_first_date, count(distinct entitlement_id) as number_of_ids
from t1
group by company_type, year_month, months_since_first_date 
order by year_month, months_since_first_date

原查询结果

company_typeyear_monthmonths_since_first_datenumber_of_ids
Small2022-011100
Medium2022-01150
Large2022-01150
Small2022-012100
Medium2022-01280
Large2022-01220

需求说明

需要新增rate列,计算同一year_month和months_since_first_date分组下,各company_type的number_of_ids占该分组总ID数的百分比。示例结果如下:

company_typeyear_monthmonths_since_first_datenumber_of_idsrate
Small2022-01110050
Medium2022-0115025
Large2022-0115025
Small2022-01210050
Medium2022-0128040
Large2022-0122010

尝试过的错误语句

count(id) * 100 / count(count(id) over() as rate

正确解决方案

要实现这个需求,需要先计算每个year_month和months_since_first_date分组的总ID数,再用各公司的ID数除以这个总数并乘以100得到占比,可通过窗口函数SUM() OVER()实现:

select 
    company_type, 
    year_month, 
    months_since_first_date, 
    count(distinct entitlement_id) as number_of_ids,
    -- 计算占比:当前公司ID数 / 同分组总ID数 * 100,保留0位小数
    round(
        count(distinct entitlement_id) * 100.0 
        / sum(count(distinct entitlement_id)) over(partition by year_month, months_since_first_date),
        0
    ) as rate
from t1
group by company_type, year_month, months_since_first_date 
order by year_month, months_since_first_date;

关键说明:

  • sum(count(distinct entitlement_id)) over(partition by year_month, months_since_first_date):计算每个year_month+months_since_first_date组合下的总ID数,作为占比计算的分母。
  • 乘以100.0是为了触发浮点数除法,避免整数除法导致的精度丢失。
  • round()函数用于控制小数位数,可根据实际需求调整保留位数。

内容的提问来源于stack exchange,提问作者ashtheinnocent

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 03:18:25