sql&postgres中同时计算avg和stddev\u pop的有效方法

8tntrjer  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(368)

stddev_pop()必须将avg()计算为标准偏差完整计算的一部分(除非有我不知道的快捷方式)。
对于上下文,目标是测试这两个geom列之间的平均值差异。
为了避免重新计算avg(),有没有办法访问它?
下面是一个查询示例:

select 
    avg(st_length(cons.geom)) as source_avg_length,
    avg(st_length(csn.geom)) as target_avg_length,
    stddev_pop(st_length(cons.geom)) as source_std_length,
    stddev_pop(st_length(csn.geom)) as target_std_length
from 
    received.conflation_osm_no_service cons,
    received.conflation_stress_network csn ;

以及 EXPLAIN ANALYZE 这让我想到,如果我请求avg()和stddev\u pop(),它只会执行avg()计算一次并重用它?:

w1jd8yoj

w1jd8yoj1#

要将两个表合并为一个结果,必须在合并前进行聚合:

select *
from 
 (  
   select 
       avg(st_length(geom)) as source_avg_length,
       stddev_pop(st_length(geom)) as source_std_length
   from received.conflation_osm_no_service cons
 ) as src
cross join
 (
   select 
       avg(st_length(geom)) as target_avg_length,
       stddev_pop(st_length(geom)) as target_std_length,
   from 
       received.conflation_stress_network csn ;
 ) as tgt

或为每个表获取一行:

select 'source' as tablename,
    avg(st_length(geom)) as avg_length,
    stddev_pop(st_length(geom)) as std_length
from 
    received.conflation_osm_no_service cons

union all

select 'target',
    avg(st_length(geom)),
    stddev_pop(st_length(geom)),
from 
    received.conflation_stress_network csn ;
jobtbby3

jobtbby32#

根据评论,我把执行速度慢归因于多个平均聚合,而实际上这是由于不必要的连接。

相关问题