如何在postgresql中计算组内的百分比?

时间:2018-05-29 05:13:49

标签: 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.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

如何添加每个公司规模的收入百分比?我想根据大小分组中的美元金额来做这件事。

实施例

Company A...Large Cap...15m = 60% (15/25)
Company A...Mid Cap...10m = 40% (10/25)

2 个答案:

答案 0 :(得分:0)

(ia.amount / sum(ia.amount))* 100为百分比

答案 1 :(得分:0)

您正在寻找一个窗口函数,即SUM() OVER()

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;