2017-03-16 2566 views
0

我将我的数据按seconditemid分组。是否有可能计算总数(所有表格数据的extcost合并)的各行的sum(extcost)百分比?PostgreSQL计算当前行数值占总数的百分比

例如我们在结果集中有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

+0

的2D查询似乎罚款,你确定每个项目具有值的> = 10% ?你只能在点后四舍五入到第一位 – cur4so

回答

0

让我们这个示例模式:

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) 
0

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

这里是没有视图的示例

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 

输出:

 
| seconditemid | percent | 
|--------------|---------| 
|   A2 | 0.55 | 
|   A1 | 0.45 | 

SQLFiddle