【问题标题】:Grouping and processing groups inside plpgsql functionsplpgsql 函数中的分组和处理组
【发布时间】:2023-03-25 17:36:01
【问题描述】:

我需要执行复杂的组处理,例如here。我从一个复杂的查询中得到一些行,行集如下所示:

关键值 -------- 富 1 富二 富 3 酒吧 10 酒吧 15 巴兹 22 巴兹 44 ...

这是我想在 plpgsql 中实现的伪代码:

result = new array()
group = new array()
current_key = null
for (record in (select * from superComplexQuery())) {
    if (current_key == null) {
        current_key = record.key
    }
    if (current_key != record.key) {
        result.add(processRows(group))
        group.clear()
        current_user = record.key
    }
    group.add(record)
}
if (group.size() > 0) {
    result.add(processRows(group))
}
return result

即,我们必须处理 3 个“foo”行,然后是 2 个“bar”行,然后是 2 个“baz 行”,等等。每个 processRows 的结果都会添加到结果集合中。

也许我应该使用另一种方法,但我不知道它必须是什么。

编辑:processRows 应该输出一条记录。因此,整个过程的输出将是一组行,其中每一行都是 processRows(group) 的结果。这个问题的第一句给出了这种计算的一个例子:Selecting positive aggregate value and ignoring negative in Postgres SQL,即计算涉及一些迭代和聚合,具有一些复杂的规则。

【问题讨论】:

  • 你能解释一下你需要processRows做什么吗?如果我们对您想要做的事情有更多了解,您很可能可以使用 GROUP BY 完成此操作。

标签: postgresql stored-procedures plpgsql


【解决方案1】:

正确的做法是使用User-Defined Aggregates

即我成功实现了自己的聚合函数,代码看起来像

select my_complex_aggregation((input_field_1, input_field_2, input_field_3)) 
from my_table
group by key

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    相关资源
    最近更新 更多