mysql string agg,如何使array_agg()像mySQL中的group_concat()一样工作

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:

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

Is there a way I can have this in 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 )

解决方案

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;

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;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值