代码之家  ›  专栏  ›  技术社区  ›  EoghanM

sql:聚合函数和字符串连接/连接[duplicate]

  •  3
  • EoghanM  · 技术社区  · 16 年前

    可能重复:
    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           |
    

    按照 join unique 是否存在任何数据库中的字符串?

    2 回复  |  直到 9 年前
        1
  •  14
  •   Michael Buen    16 年前
    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
    
        2
  •  4
  •   Bob Folkerts    14 年前

    postresql9中有一个字符串\u 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)