使用Total来获得PostgreSQL中组的百分比的最佳方法是什么

时间:2016-05-15 19:28:10

标签: sql postgresql

在excel和其他类似软件中,您可以使用总计来获得百分比。任何人都可以说出复制全部功能的最有效方法是什么。

我使用了嵌套查询但是我得不到正确的结果

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

3 个答案:

答案 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

答案 1 :(得分:1)

你所做的分工是一个整数除法。为了获得小数输出,您应该将其中一个计数转换为浮点数,如下所示:

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

或简写:

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

答案 2 :(得分: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