2017-03-16 22 views
0

私はデータをseconditemidでグループ化します。合計行(すべてのテーブルデータのエクステントを組み合わせたもの)に対する各行の割合を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%を持っているあなたは確かです?あなたはポイントの後に1桁目に切り上げます – 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

あなたの2番目のクエリは、[OK]をする必要がありますがinteger division truncates the resultsので、あなたが戻って0秒を得ました。合計値を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