Postgres直方图添加记录

问题描述 投票:0回答:1

使用 Postgres 15 创建直方图,得到奇怪的结果。

我的列有 25 条记录,具体取决于

nbins
cte 中的
bin_params
值 当我对
'freq'
列求和时,我得到不同的记录计数。当
nbins
= 12 或 13 时,我得到太多(26)。当
nbins
= 11 时,我得到正确的计数 25.

我尝试过但导致类似混乱结果的另一种方法是将

min(x)
cte 中的
bin_params
乘以 .99、.999 和 .9999999。当我改变小数位数时,我会返回不同的记录计数,与上述行为相同。

我想要的解决方案是

sum(freq)
= # 或列中的记录。

我已经阅读/尝试过来自hereherehere以及许多其他解决方案。下面的代码与我找到的可行解决方案一样接近。

谢谢你帮助我。

这是我的代码(底部的示例数据):

with rnorm as
                (SELECT 
                        my_col::numeric as x
                        from my_table
                ),
bin_params as
                (select 
                        min(x) as min_x 
                        ,max(x) as max_x
                        ,13 as nbins
                from rnorm),
temp_bins as
                (SELECT
                        generate_series(min_x::numeric, max_x::numeric, ((max_x - min_x) / nbins)::numeric) as bin
                from bin_params
                ),
bin_range as
                ( select
                        lag(bin) over (order by bin) as low_bin
                        ,b.bin as high_bin

                    from temp_bins b
                ),
frequency_table as
        (   select
                        b.low_bin
                        ,b.high_bin
                        ,count(*) as freq
                from bin_range b
                left join rnorm r
                        on r.x <= b.high_bin
                        and r.x > b.low_bin
                where   b.low_bin is not null
                        and b.high_bin is not null
                group by
                        b.low_bin
                        ,b.high_bin
                        ,count_x
                order by b.low_bin
        )

select * from frequency_table

我的表:

|"my_col"|
|------|
|74.03|
|73.995|
|73.988|
|74.002|
|73.992|
|74.009|
|73.995|
|73.985|
|74.008|
|73.998|
|73.994|
|74.004|
|73.983|
|74.006|
|74.012|
|74|
|73.994|
|74.006|
|73.984|
|74|
|73.988|
|74.004|
|74.01|
|74.015|
|73.982|
postgresql histogram
1个回答
0
投票

三个问题

首先,

generate_series()
可能不包含
stop
参数,这取决于步骤。请参阅Set Returning Functions中的第三个示例。您可以将
step
添加到第二个参数以确保所有值都在生成的范围内。

其次,严格不等式

r.x > b.low_bin
省略了
min_x
值。对生成的系列使用较小的
start
参数。

第三,即使范围内没有值(因为左连接),

count(*) as freq
也会给出 1。应该是
count(x) as freq
.

© www.soinside.com 2019 - 2024. All rights reserved.