Sql: aggregate functions and string concatenation / concatenation

Possible duplicate:
How to bind string field strings in a PostgreSQL group by query?

(I am using postgres)

Are there any aggregate functions that work with strings?

I want to write a query line by line

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

Given these two tables:

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

The request should be returned:

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

Are there functions that are along rows joinand uniqueexist in any DB for rows?

+3
source share
2 answers
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
+10
source

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)
+4

Source: https://habr.com/ru/post/1745753/


All Articles