plpgsql 函数内的分组和处理组

发布于 2024-12-05 23:49:14 字数 1148 浏览 0 评论 0原文

我需要执行复杂的组处理,例如此处< /a>.我从复杂查询中获取一些行,行集如下所示:

key val
-------
foo 1
foo 2
foo 3
bar 10
bar 15
baz 22
baz 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” rows”等。每个 processRows 的结果都会添加到结果集合中。

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

编辑:processRows 应该输出一条记录。因此,整个过程的输出将是一组行,其中每一行都是 processRows(group) 的结果。此问题的第一句给出了此类计算的一个示例:Postgres SQL 中选择正聚合值并忽略负聚合,即计算涉及一些复杂规则的迭代和聚合。

I need to perform a sophisticated group processing, like here. I get some rows from a complex query, the row set looks like this:

key val
-------
foo 1
foo 2
foo 3
bar 10
bar 15
baz 22
baz 44
...

And here is a pseudocode I want to implement in 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

I.e., we must process 3 "foo" rows, then 2 "bar" rows, then 2 "baz rows" etc. And result of each processRows is added to resulting collection.

Maybe I should use another approach, but I don't know what it must be.

EDIT: processRows should output a record. Thus, the output of the whole procedure will be a set of rows, where each row is a result of processRows(group). One example of such calculation is given in first sentence of this question: Selecting positive aggregate value and ignoring negative in Postgres SQL , i.e. the calculation involves some iteration and aggregation with some complex rules.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

帅的被狗咬 2024-12-12 23:49:14

正确的方法是使用 用户定义的聚合

即我成功实现了我的自己的聚合函数,代码如下

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

The right approach was to use User-Defined Aggregates

I.e. I successfully implemented my own aggregate function and the code looks like

select my_complex_aggregation((input_field_1, input_field_2, input_field_3)) 
from my_table
group by key
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文