简体   繁体   中英

How to split the rows to groups with 'group concat' and 'group by' query in MySQL?

I have a database table as below.

--id-- --name-- --age--
   1     test      10
   2     test      15
   3     test      20

And i want to split this table rows with Group By and Group Concat queries. For example,

SELECT name, GROUP_CONCAT(age) as ages FROM 'table' GROUP BY name

The output of this query as below:

--name-- --ages--
  test     10,15,20

But I want an output like below. So I want to divide into 2 groups.

--name-- --ages--
  test      10,15
  test      20

Is it possible? I hope I was able to explain.

select name, group_concat(age) as ages from (
  select id, name, age, 
    round(row_number() over (partition by name order by id) / 2) as g 
    from t
  ) as t group by name, g;
+------+-------+
| name | ages  |
+------+-------+
| test | 10,15 |
| test | 20    |
+------+-------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM