如何在postgresql中计算group by中的百分比?
我有一个对公司名称、规模和收入进行分组的查询。这是我的疑问:如何在postgresql中计算group by中的百分比?,sql,postgresql,Sql,Postgresql,我有一个对公司名称、规模和收入进行分组的查询。这是我的疑问: with Test as (select id.name as Company ,CASE WHEN li.segment = 'Large' then 'Large Cap' WHEN li.segment = 'Medium' then 'Mid Cap' WHEN li.segment = 'Small' then 'Small Cap' else NULL end as Size ,sum(ia.amo
with Test as
(select
id.name as Company
,CASE WHEN li.segment = 'Large' then 'Large Cap'
WHEN li.segment = 'Medium' then 'Mid Cap'
WHEN li.segment = 'Small' then 'Small Cap' else NULL end as Size
,sum(ia.amount) as Revenue
from base.company_rev ia
join base.company_detail id on id.company_account_id = ia.company_account_id
left join base.product_issued li on li.product_id = ia.product_id
where 1 = 1
and ia.create_date::date between '2018-05-01' and '2018-05-31'
group by id.name, li.segment
order by 1, 2, 3)
select *
from Test
group by company, size, revenue
order by 1, 2, 3
我如何增加每家公司规模所占收入的百分比?我想根据尺码分组中的美元金额来做
前
(ia.amount/sum(ia.amount))*100(百分比)您正在寻找一个窗口函数,即
sum()OVER()
为什么要对公司进行两次聚合?
orderby
在子查询中(在您的WITH
子句中)是多余的。主查询中的分组依据
也是多余的,因为它包含所有列,因此什么也不做。最后:使用positionalORDER BY
被认为是不好的风格。改用名字,这太完美了。谢谢
Company A...Large Cap...15m = 60% (15/25)
Company A...Mid Cap...10m = 40% (10/25)
with test as
(
select
id.name as company
,case when li.segment = 'Large' then 'Large Cap'
when li.segment = 'Medium' then 'Mid Cap'
when li.segment = 'Small' then 'Small Cap'
else null end as size
,sum(ia.amount) as revenue
from base.company_rev ia
join base.company_detail id on id.company_account_id = ia.company_account_id
left join base.product_issued li on li.product_id = ia.product_id
where 1 = 1
and ia.create_date::date between date '2018-05-01' and date '2018-05-31'
group by id.name, li.segment
)
select
company,
size,
revenue,
revenue / sum(revenue) over (partition by company) * 100 as percentage
from test
order by company, size, revenue;