plpgsql 函数内的分组和处理组
我需要执行复杂的组处理,例如此处< /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技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正确的方法是使用 用户定义的聚合
即我成功实现了我的自己的聚合函数,代码如下
The right approach was to use User-Defined Aggregates
I.e. I successfully implemented my own aggregate function and the code looks like