【问题标题】:postgres: aggregate function on multiple fieldspostgres:多个字段的聚合函数
【发布时间】:2019-03-27 14:36:44
【问题描述】:

我的桌子是:

price: numeric, time: timestamp, type: integer

我想按类型分组,并为每个组找到最高价格和最早(按时间)价格。

从计算的角度来看,这是一个简单的线性/类约简操作。但是如何在 postgres 中完成呢?有这样的现有功能吗?我必须创建自己的聚合吗?我应该像$time-$price 这样将两个字段编码为一个字段并从中找到最小值吗?

【问题讨论】:

    标签: sql postgresql group-by aggregate


    【解决方案1】:

    嗯。 Postgres 没有first() 聚合函数,但你可以使用数组来代替:

    select type,
           max(price),
           array_agg(price order by time asc)[1] as earliest_price
    from t
    group by type;
    

    编辑:

    还有其他方法,比如:

    select distinct on (type) type,
           max(price) over (partition by type),
           price
    from t
    order by type, time asc;
    

    【讨论】:

    • 但是first() 聚合很容易实现:wiki.postgresql.org/wiki/First/last_(aggregate)
    • 但这需要 O(n) 内存,对吧?如果每种类型都包含很多行,这可能需要大量内存。而在计算上,它可以在 O(1) 内存中完成而不存储所有行 - 在 postgres 中是否可能?
    • @piotrek 。 . .谷歌 BigQuery 要好得多。它支持array_agg() 中的LIMIT 子句以避免该问题。
    猜你喜欢
    • 1970-01-01
    • 2017-05-06
    • 2013-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多