2010-05-17 87 views
3

可能重复:
How to concatenate strings of a string field in a PostgreSQL ‘group by’ query?SQL:聚合函数和字符串连接/串联

(我使用的是Postgres)

是否有处理字符串的任何聚合函数?

我想写沿

select table1.name, join(' - ', unique(table2.horse)) as all_horses 
from table1 inner join table2 on table1.id = table2.fk 
group by table1.name 

线路查询鉴于这2个表:

| table1   |    | table2     | 
| id (pk) | name |    | id (pk) | horse | fk | 
+---------+-------+    +---------+---------+-------+ 
|  1 | john |    |  1 | redrum |  1 | 
|  2 | frank |    |  2 | chaser |  1 | 
            |  3 | cigar |  2 | 

查询应返回:

| name | all_horses  | 
+--------+-------------------+ 
| john | redrum - chaser | 
| frank | cigar   | 

做功能沿joinunique行中是否存在任何字符串数据库?

回答

10
select table1.name, 
    array_to_string(array_agg(distinct table2.horse), ' - ') as all_horses 
from table1 inner join table2 on table1.id = table2.fk 
group by table1.name 
+0

嗯似乎并不具备这些功能定义 - 你可以帮我收的问题,因为它是的43870重复? – EoghanM 2010-05-17 12:10:12

+0

尝试升级到8.4,array_agg是内置的。关于这个问题,它需要5个关闭,截至目前只有1个关闭了你的问题。你可以删除你自己的问题 – 2010-05-17 12:22:43

4

PostreSQL 9中有一个string_agg查询。我有一个地区表和一个部门表,其中一个地区有多个部门(例如法国)。我的样本查询:

select r.name, string_agg(d.name, ',') 
from regions r 
join departments d on d.region = r.code 
group by r.name 
order by r.name; 

这使我行像

Picardie Aisne,Oise,Somme 

事情变得有点混乱,如果你婉改变聚集串的顺序。这工作,但我有任何疑问的病理厌恶具有鲜明:

select distinct r.name as region, string_agg(d.name, ',') over w as departments 
from regions r 
join departments d on d.region = r.code 
window w as (partition by r.name order by d.name desc 
    rows between unbounded preceding and unbounded following)