【问题标题】:How do I calculate percentages within group by in postgresql?如何在postgresql中计算group by中的百分比?
【发布时间】:2018-05-29 05:13:48
【问题描述】:

我有一个将公司名称、规模和收入分组的查询。这是我的查询:

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)

【问题讨论】:

  • 你为什么要在公司聚合两次?
  • ORDER BY 在子查询中(在您的 WITH 子句中)是多余的。主查询中的 GROUP BY 也是多余的,因为它包含所有列,因此什么也不做。最后:使用定位ORDER BY 被认为是不好的风格。请改用名称。

标签: sql postgresql


【解决方案1】:

你正在寻找一个窗口函数,即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;

【讨论】:

  • 这是完美的。谢谢!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 2016-07-02
    • 2011-09-06
    • 1970-01-01
    • 2020-10-20
    • 2017-05-13
    • 1970-01-01
    • 2013-10-27
    • 1970-01-01
    相关资源
    最近更新 更多