首页 > 解决方案 > 可以在过滤子句中进行额外的聚合吗?(PostgreSQL)

问题描述

我想写这样的东西:

  select 
    "id", 
    "plant", 
    "product", 
    "uom", 
    count(*) as transactions_count,
    avg(("invoice_price" / "quantity")) filter (where ("date" == max(date))  as "LAST_GUIDANCE", -- I want group by date only for this
  from "transactions"
  group by 
    "id", 
    "plant", 
    "product", 
    "uom"

我想计算最后一次指导,但仅适用于最后日期的行。

问题是我不能将“日期”添加到分组依据,因为我只希望这个分组仅用于 last_guidance.. 可以在 Postgres 中以某种方式轻松编写它(例如,使用“over”)或者我必须创建过于分离的查询然后加入他们?

感谢您的回答

标签: sqlpostgresql

解决方案


这是不允许的。错误信息很清楚:

错误:FILTER LINE 1 中不允许使用聚合函数:选择 count(*) 过滤器(其中 x = max(x))

也不允许使用窗口函数。

您可以使用子查询来计算最大日期:

select id, plan, product, uom,
       count(*) as transactions_count,
       avg(invoice_price / quantity) filter (where date = max_date)  as LAST_GUIDANCE
from (select t.*, 
             max(date) over (partition by id, plan, product, uom) as max_date
      from transactions t
     ) t
group by id, plan, product, uom;

请注意,我删除了双引号。不要转义列名。这只会使查询更难编写和阅读。


推荐阅读