Search code examples
mysqlgroup-concat

Mysql: Concatenate specific number of rows per result


I have a table with 400K records with single column with numbers. I need result set concatenated by 5000 records as strings. Table DDL: create table temp_table (entity_id INT NOT NULL); Example insert statements:

insert into temp_table values(3468641);
insert into temp_table values(3375532);
insert into temp_table values(3346707);
insert into temp_table values(3473709);
insert into temp_table values(3453158);
insert into temp_table values(3357617);
insert into temp_table values(337046);
insert into temp_table values(3561951);
insert into temp_table values(3409571);
insert into temp_table values(355078);
insert into temp_table values(356369);
insert into temp_table values(352354);
insert into temp_table values(3494237);

Expected output(concatenate 5 records per row)

'341822','3468641','3375532','3346707','3473709'
'3453158','3357617','337046','3561951','3409571'
'355078','356369','352354','3494237'

How can achieve above in mysql?


Solution

  • Ideally there should exist a second column which provides the ordering and grouping you want between each set of (up to 5) numbers. Assuming that such an id column exists, we can try the following aggregation approach:

    WITH cte AS (
        SELECT *, ROW_NUMBER() OVER (ORDER BY id) rn
        FROM temp_table
    )
    
    SELECT GROUP_CONCAT(entity_id) AS output
    FROM cte
    GROUP BY FLOOR((rn - 1) / 5);