PostgreSQL-来自同一函数调用的多个聚合查询

PostgreSQL-来自同一函数调用的多个聚合查询,sql,postgresql,Sql,Postgresql,我有一个函数,它从表中返回一组: 创建或替换函数get_assoc_addrs_from_bbl_bbl text 将wow_bldgs的集合返回为$$ 从wow_bldgs中选择bldgs.*作为bldgs ... $$语言SQL稳定; 以下是表格将返回的内容示例: 现在我正在编写一个聚合函数,它将只返回一行,其中包含关于该函数返回的表的各种聚合数据点。以下是我当前的工作和天真示例: 选择 countdistinct注册ID为bldgs, 单位作为单位, Roundavgyearlbuilde

我有一个函数,它从表中返回一组:

创建或替换函数get_assoc_addrs_from_bbl_bbl text 将wow_bldgs的集合返回为$$ 从wow_bldgs中选择bldgs.*作为bldgs ... $$语言SQL稳定; 以下是表格将返回的内容示例:

现在我正在编写一个聚合函数,它将只返回一行,其中包含关于该函数返回的表的各种聚合数据点。以下是我当前的工作和天真示例:

选择 countdistinct注册ID为bldgs, 单位作为单位, Roundavgyearlbuilded,1岁, 从中选择firstcorpname 选择unnestcorpnames作为corpname 从bbl'3012380016'获取助理地址 按公司名称分组按计数排序*说明限制1 作为topcorp, 从中选择firstbusinessaddr 选择unnestbusinesaddrs作为businessaddr 从bbl'3012380016'获取助理地址 按业务分组添加按计数的订单*说明限制1 rbas作为topbusinessaddr 从联合地址获取联合地址 如您所见,对于需要自定义分组/排序方法的两个子查询,我需要重复调用以从\u bbl获取\u assoc\u addrs\u。理想情况下,我正在寻找一种能够避免重复调用的结构,因为函数需要大量处理,并且我希望能够容纳任意数量的子查询。我研究过CTE和窗口表达式等,但没有运气

有什么建议吗?谢谢大家!

创建简单的:

它将数组值聚合到单个dim数组中。例如:

# with t(x) as (values(array[1,2]),(array[2,3,4])) select array_agg2(x) from t;
┌─────────────┐
│ array_agg2  │
╞═════════════╡
│ {1,2,2,3,4} │
└─────────────┘
之后,您的查询可以重写为

SELECT 
  count(distinct registrationid) as bldgs,
  sum(unitsres) as units,
  round(avg(yearbuilt), 1) as age,
  (SELECT first(corpname) FROM (
    SELECT * FROM unnest(array_agg2(corpnames)) as corpname
    GROUP BY corpname ORDER BY count(*) DESC LIMIT 1
  ) corps) as topcorp,
  (SELECT first(businessaddr) FROM (
    SELECT * FROM unnest(array_agg2(businessaddrs)) as businessaddr
    GROUP BY businessaddr ORDER BY count(*) DESC LIMIT 1
  ) rbas) as topbusinessaddr
FROM get_assoc_addrs_from_bbl('3012380016') assocbldgs
当然,如果我正确理解您的目标,请创建简单的:

它将数组值聚合到单个dim数组中。例如:

# with t(x) as (values(array[1,2]),(array[2,3,4])) select array_agg2(x) from t;
┌─────────────┐
│ array_agg2  │
╞═════════════╡
│ {1,2,2,3,4} │
└─────────────┘
之后,您的查询可以重写为

SELECT 
  count(distinct registrationid) as bldgs,
  sum(unitsres) as units,
  round(avg(yearbuilt), 1) as age,
  (SELECT first(corpname) FROM (
    SELECT * FROM unnest(array_agg2(corpnames)) as corpname
    GROUP BY corpname ORDER BY count(*) DESC LIMIT 1
  ) corps) as topcorp,
  (SELECT first(businessaddr) FROM (
    SELECT * FROM unnest(array_agg2(businessaddrs)) as businessaddr
    GROUP BY businessaddr ORDER BY count(*) DESC LIMIT 1
  ) rbas) as topbusinessaddr
FROM get_assoc_addrs_from_bbl('3012380016') assocbldgs

当然,如果我正确理解了您的目标

为什么不创建一个包含从bbl公开获取的所有信息的表?为什么不创建一个包含从bbl公开获取的所有信息的表?这很有效!我有一个单独的字段处理json数组,它通过一个横向子查询进行了更多的工作。谢谢这管用!我有一个单独的字段处理json数组,它通过一个横向子查询进行了更多的工作。谢谢