2016-05-15 21 views
0

在excel和其他類似軟件中,您可以使用total來獲取百分比。任何人都可以說出什麼是複製總功能的最有效方法。什麼是使用Total獲得PostgreSQL中組的百分比的最佳方式

我已經使用嵌套查詢,但我沒有得到正確的結果

select retpre04recency, 
count(*) as CustomerCount, 
(select count(*) from extractsummary) as Total, 
round(count(*)/(select count(*) from extractsummary),2) as CustomerCount 
    from extractsummary 
    group by retpre04recency 
    order by retpre04recency asc 
    ; 

我的百分比列結果是零。誰能幫忙?

enter image description here

回答

1

這是一個類型的問題。表達式

count(*) 

結果類型bigint。表達式

(select count(*) from extractsummary) 

也導致類型bigint。與某些編程語言(例如R)不同,PostgreSQL中的除法操作符不會自動將整數操作數提升爲小數類型。所以你必須自己施放它。

select 
    retpre04recency, 
    count(*) as CustomerCount, 
    (select count(*) from extractsummary) as Total, 
    round(count(*)::numeric/(select count(*) from extractsummary),2) as CustomerCount 
from 
    extractsummary 
group by 
    retpre04recency 
order by 
    retpre04recency asc 
; 

例子:

drop table if exists extractsummary; 
create table extractsummary (retpre04recency int); 
insert into extractsummary (retpre04recency) values (1), (1), (2), (2), (2), (3), (3), (3), (3), (4), (4), (4), (5), (5), (5), (5), (5), (6), (6), (6), (99); 

select 
    retpre04recency, 
    count(*) as CustomerCount, 
    (select count(*) from extractsummary) as Total, 
    round(count(*)::numeric/(select count(*) from extractsummary),2) as CustomerCount 
from 
    extractsummary 
group by 
    retpre04recency 
order by 
    retpre04recency asc 
; 

output

+0

謝謝!作品! 也是這樣做的最有效的方法?我的意思是嵌套查詢總數 –

1

我不知道您有什麼問題,但分析功能是比子查詢簡單的方法:

select retpre04recency, 
     count(*) as CustomerCount, 
     sum(count(*)) over() as Total, 
     round(count(*)/sum(count(*)) over(), 2) as CustomerCount 
from extractsummary 
group by retpre04recency 
order by retpre04recency asc 
+0

謝謝!是的,我比較了這兩個查詢。子查詢大約需要260毫秒,分析功能需要大約190毫秒 –

+0

Gordon, 您能否爲窗口函數提供很好的教程 –

+0

不完全是教程,但文檔非常好:http://www.postgresql.org/docs/9.5/static /tutorial-window.html。也可能會發現http://www.postgresql.org/docs/9.5/static/functions-window.html有用。 –

1

你做除法是整數除法。爲了得到小數輸出,你應該投計數的一個浮點數,就像這樣:

round(cast(count(*) as numeric)/(select count(*) from extractsummary),2) 

或短手:

round(count(*)::numeric/(select count(*) from extractsummary),2) 
+0

謝謝!工作沒有四捨五入。錯誤是「函數輪(雙精度,整數)不存在:」 我該怎麼做舍入 –

+0

啊,轉換爲數字而不是浮點數然後。相應地更新我的答案。對於那個很抱歉。 – trincot

相關問題