【问题标题】:PostgreSQL calculate percentage of current row's value over sum of totalsPostgreSQL计算当前行的值占总数的百分比
【发布时间】:2017-08-08 06:28:29
【问题描述】:

我按seconditemid 对我的数据进行分组。是否可以计算每行的sum(extcost) 占总和(所有表数据的 extcost 总和)的百分比?

例如我们在结果集中有2行,A1总共4500,A2总共5500,总计应该是10000,A1占45%,A2占55%。

seconditemid|ratio
--------------------
A1          |.45
--------------------
A2          |.55

我的查询是

select seconditemid,  
    round(100.0*(
        sum(case when seconditemid = ---the current row's seconditemid
        then 1 else 0 end)/sum(extcost)
    ),1) as ratio
from inventory_fact f inner join item_master_dim i using (itemmasterkey)
where transtypekey = 1
group by seconditemid
order by 2 desc;

那行不通。我尝试先创建一个视图

create view v1 as(
    select sum(extcost) as sumExtcost from inventory_fact
);

并从中选择

select seconditemid, round(100.0*(
        sum(extcost)/sum(v1.sumextcost)
    ),1) as ratio
from from inventory_fact f inner join item_master_dim i using (itemmasterkey), v1
where transtypekey = 1
group by seconditemid
order by 2 desc;

那么每列的比例变成0。

【问题讨论】:

  • 2d 查询看起来不错,你确定每个项目都有 >=10% 的价值吗?您只在点后四舍五入到第 1 位

标签: postgresql


【解决方案1】:

您的第二个查询应该没问题,但您得到了0s,因为integer division truncates the results。您需要将总和值明确转换为 floats。

这是一个没有视图的例子

SELECT g.seconditemid, g.extcost::float / t.total::float percent -- << here
  FROM (
  SELECT seconditemid, SUM(extcost) extcost
    FROM inventory_fact
   GROUP BY seconditemid
) g CROSS JOIN (
  SELECT SUM(extcost) total
    FROM inventory_fact
) t
 ORDER BY percent DESC

输出:

|次项|百分比 | |--------------|----------| | A2 | 0.55 | | A1 | 0.45 |

SQLFiddle

【讨论】:

    【解决方案2】:

    让我们以这个示例架构为例:

    CREATE TABLE c (
        seconditemid text,
        total int
    );
    
    INSERT INTO c (seconditemid, total) VALUES ('A1', 4500);
    INSERT INTO c (seconditemid, total) VALUES ('A2', 5500);
    

    这里是查询:

    SELECT seconditemid, total, 
           total::float / (SUM(total) OVER()) as ratio
    FROM c;
    

    ->

     seconditemid | total | ratio 
    --------------+-------+-------
     A1           |  4500 |  0.45
     A2           |  5500 |  0.55
    (2 rows)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      相关资源
      最近更新 更多