Eog*_*anM 3 sql string postgresql aggregate
(我正在使用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           |
是否存在于字符串的任何DB 中join并且unique存在的功能?
Mic*_*uen 13
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
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)
| 归档时间: | 
 | 
| 查看次数: | 13239 次 | 
| 最近记录: |