sql:聚合函数&字符串连接/连接

时间:2010-05-17 09:20:22

标签: sql postgresql string aggregate

  

可能重复:
  How to concatenate strings of a string field in a PostgreSQL ‘group by’ query?

(我正在使用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

鉴于这两个表:

| 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行的函数吗?

2 个答案:

答案 0 :(得分:12)

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

答案 1 :(得分: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)