postgresql 如何使 array_agg() 像 mySQL 中的 group_concat() 一样工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4054559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:42:44  来源:igfitidea点击:

how to make array_agg() work like group_concat() from mySQL

postgresqlarray-agg

提问by user491575

So I have this table:

所以我有这张表:

create table test (
   id integer, 
   rank integer,
   image varchar(30)
); 

Then some values:

然后是一些值:

id | rank | image   
---+------+-------  
 1 |    2 | bbb  
 1 |    3 | ccc  
 1 |    1 | aaa  
 2 |    3 | c  
 2 |    1 | a  
 2 |    2 | b  

I want to group them by id and concatenate the image name in the order given by rank. In mySQL I can do this:

我想按 id 对它们进行分组,并按照排名给出的顺序连接图像名称。在 mySQL 中,我可以这样做:

  select id, 
         group_concat( image order by rank asc separator ',' ) 
    from test 
group by id;

And the output would be:

输出将是:

1 aaa,bbb,ccc
2 a,b,c
有没有办法可以在 postgresql 中使用它?

If I try to use array_agg()the names will not show in the correct order and apparently I was not able to find a way to sort them. (I was using postgres 8.4 )

如果我尝试使用array_agg()名称将不会以正确的顺序显示,显然我无法找到对它们进行排序的方法。(我使用的是 postgres 8.4 )

回答by Jason Weathered

In PostgreSQL 8.4 you cannot explicitly order array_aggbut you can work around it by ordering the rows passed into to the group/aggregate with a subquery:

在 PostgreSQL 8.4 中,您不能显式排序,array_agg但可以通过使用子查询对传递到组/聚合的行进行排序来解决它:

SELECT id, array_to_string(array_agg(image), ',')
FROM (SELECT * FROM test ORDER BY id, rank) x
GROUP BY id;

In PostgreSQL 9.0 aggregate expressions can have an ORDER BYclause:

在 PostgreSQL 9.0 聚合表达式中可以有一个ORDER BY子句:

SELECT id, array_to_string(array_agg(image ORDER BY rank), ',')
FROM test
GROUP BY id;