PostgreSQL array_agg 顺序
表“动物”:
animal_name animal_type
Tom Cat
Jerry Mouse
Kermit Frog
查询:
SELECT
array_to_string(array_agg(animal_name),';') animal_names,
array_to_string(array_agg(animal_type),';') animal_types
FROM animals;
预期结果:
Tom;Jerry;Kerimt, Cat;Mouse;Frog
OR
Tom;Kerimt;Jerry, Cat;Frog;Mouse
我能否确定第一个聚合函数中的顺序始终与第二个聚合函数中的顺序相同。 我的意思是我不想得到:
Tom;Jerry;Kermit, Frog;Mouse,Cat
Table 'animals':
animal_name animal_type
Tom Cat
Jerry Mouse
Kermit Frog
Query:
SELECT
array_to_string(array_agg(animal_name),';') animal_names,
array_to_string(array_agg(animal_type),';') animal_types
FROM animals;
Expected result:
Tom;Jerry;Kerimt, Cat;Mouse;Frog
OR
Tom;Kerimt;Jerry, Cat;Frog;Mouse
Can I be sure that order in first aggregate function will always be the same as in second.
I mean I would't like to get:
Tom;Jerry;Kermit, Frog;Mouse,Cat
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 ORDER BY,就像手册中的示例:
Use an ORDER BY, like this example from the manual:
如果您使用的是 PostgreSQL 版本 9.0 然后:
来自:http://www.postgresql.org/docs/8.4 /static/functions-aggregate.html
因此,在您的情况下,您将编写:
array_agg 的输入将是无序的,但两列中的输入都是相同的。如果您愿意,可以向子查询添加一个
ORDER BY
子句。If you are on a PostgreSQL version < 9.0 then:
From: http://www.postgresql.org/docs/8.4/static/functions-aggregate.html
So in your case you would write:
The input to the array_agg would then be unordered but it would be the same in both columns. And if you like you could add an
ORDER BY
clause to the subquery.根据 Tom Lane 的说法:
因此,我认为可以假设查询中的所有聚合(其中没有一个使用 ORDER BY)将以相同的顺序看到输入数据。但顺序本身未指定(这取决于 FROM 子句提供行的顺序)。
来源:PostgreSQL 邮件列表
According to Tom Lane:
So I think it's fine to assume that all the aggregates, none of which uses ORDER BY, in your query will see input data in the same order. The order itself is unspecified though (which depends on the order the FROM clause supplies rows).
Source: PostgreSQL mailing list
这样做:
Do this: