如何在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_type | year_month | months_since_first_date | number_of_ids |
|---|---|---|---|
| Small | 2022-01 | 1 | 100 |
| Medium | 2022-01 | 1 | 50 |
| Large | 2022-01 | 1 | 50 |
| Small | 2022-01 | 2 | 100 |
| Medium | 2022-01 | 2 | 80 |
| Large | 2022-01 | 2 | 20 |
需求说明
需要新增rate列,计算同一year_month和months_since_first_date分组下,各company_type的number_of_ids占该分组总ID数的百分比。示例结果如下:
| company_type | year_month | months_since_first_date | number_of_ids | rate |
|---|---|---|---|---|
| Small | 2022-01 | 1 | 100 | 50 |
| Medium | 2022-01 | 1 | 50 | 25 |
| Large | 2022-01 | 1 | 50 | 25 |
| Small | 2022-01 | 2 | 100 | 50 |
| Medium | 2022-01 | 2 | 80 | 40 |
| Large | 2022-01 | 2 | 20 | 10 |
尝试过的错误语句
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
相关产品推荐
相关产品推荐

