【发布时间】: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