2016-05-15 106 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

相关问题