Skip to content

GROUP_CONCAT函数

MySQL数据库的group_concat函数首先根据group by指定的列进行分组,然后将同一组的列集中显示,并且用分隔符分隔。由函数参数(字段名)决定要返回的列。对于group_concat函数,可以采用虚谷数据库的WM_CONCAT函数进行替代。

  • MySQL数据库GROUP_CONCAT函数

    SQL> with temp as(
            select '中国' nation ,'江苏' city from dual union all
            select '中国' nation ,'上海' city from dual union all
            select '中国' nation ,'北京' city from dual union all
            select '美国' nation ,'纽约' city from dual union all
            select '美国' nation ,'波士顿' city from dual union all
            select '日本' nation ,'东京' city from dual
          )
          select nation,group_concat(DISTINCT city order by city separator ',') as Cities
          from temp
          group by nation;
        +------+--------+
        nation | Cities |
        +------+--------+
        中国    |上海,北京,江苏|
        日本    |东京      |
        美国    |波士顿,纽约  |
  • 虚谷数据库WM_CONCAT函数
    SQL> with temp as(
            select '中国' nation ,'江苏' city from dual union all
            select '中国' nation ,'上海' city from dual union all
            select '中国' nation ,'北京' city from dual union all
            select '美国' nation ,'纽约' city from dual union all
            select '美国' nation ,'波士顿' city from dual union all
            select '日本' nation ,'东京' city from dual
          )
          select nation,wm_concat(city) as Cities
          from temp
          group by nation;
        +------+--------+
        NATION | CITIES |
        +------+--------+
        中国    |江苏,上海,北京|
        日本    |东京      |
        美国    |纽约,波士顿  |