PostgreSQL array_agg命令

前端之家收集整理的这篇文章主要介绍了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
如果你是一个Postgresql版本< 9.0然后: From: http://www.postgresql.org/docs/8.4/static/functions-aggregate.html

In the current implementation,the order of the input is in principle unspecified. Supplying the input values from a sorted subquery will usually work,however. For example:

SELECT xmlagg(x) FROM (SELECT x FROM test ORDER BY y DESC) AS tab;

所以在你的情况下你会写:

SELECT
array_to_string(array_agg(animal_name),';') animal_types
FROM (SELECT animal_name,animal_type FROM animals) AS x;

array_agg的输入将是无序的,但是在两个列中都是相同的。如果你喜欢,你可以添加一个ORDER BY子句到子查询

原文链接:https://www.f2er.com/postgresql/193575.html

猜你在找的Postgre SQL相关文章