2017-03-16 212 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