问题描述
所以我有这个表:
create table test (
id integer,
rank integer,
image varchar(30)
);
然后输入一些值:
id | rank | image
---+------+-------
1 | 2 | bbb
1 | 3 | ccc
1 | 1 | aaa
2 | 3 | c
2 | 1 | a
2 | 2 | b
我想按id将它们分组,然后按等级给定图像名称。在mySQL中,我可以执行以下操作:
I want to group them by id and concatenate the image name in the order given by rank. In mySQL I can do this:
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中使用它?
Is there a way I can have this in postgresql?
如果我尝试使用 array_agg(),名称将不会以正确的顺序显示,而且显然我无法找到一种方法对它们进行排序。 (我使用的是Postgres 8.4)
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 )
推荐答案
在PostgreSQL 8.4中,您不能显式地订购 array_agg
,但您可以通过使用子查询对传递到组/聚合中的行进行排序来解决此问题:
In PostgreSQL 8.4 you cannot explicitly order array_agg
but you can work around it by ordering the rows passed into to the group/aggregate with a subquery:
SELECT id, array_to_string(array_agg(image), ',')
FROM (SELECT * FROM test ORDER BY id, rank) x
GROUP BY id;
在PostgreSQL 9.0中,聚合表达式可以具有 ORDER BY
子句:
In PostgreSQL 9.0 aggregate expressions can have an ORDER BY
clause:
SELECT id, array_to_string(array_agg(image ORDER BY rank), ',')
FROM test
GROUP BY id;
这篇关于如何使array_agg()像mySQL中的group_concat()一样工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!