我將我的數據按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
的2D查詢似乎罰款,你確定每個項目具有值的> = 10% ?你只能在點後四捨五入到第一位 – cur4so