sql - 可以在过滤子句中进行额外的聚合吗?(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”)或者我必须创建过于分离的查询然后加入他们?
感谢您的回答
解决方案
这是不允许的。错误信息很清楚:
错误: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;
请注意,我删除了双引号。不要转义列名。这只会使查询更难编写和阅读。
推荐阅读
- python-3.x - 如何在本地连接到 azure mongo db?
- python - 在 Tensorflow 中的 batch_norm 层上应用 tf.image.per_image_standardization() 的好处?
- php - PHP 7.2.4 无法连接到我的 MySQL 8.0
- python - 分析对象列表中的数据
- javascript - Javascript显示属性不起作用
- python - 修复错误:无法从其他机器加载泡菜文件
- php - 同时使用 For 和 Foreach (在同一个循环中使用键和值/在一定数量的步骤后中断)
- python - Boto3 创建没有密钥对的实例
- mysql - 创建索引时,具有 mysql 数据库迁移的实体框架失败
- oracle - 两个时间戳之间的Oracle查询不返回记录