Home > Blockchain >  Concatenate previous all rows until current row
Concatenate previous all rows until current row

Time:11-29

I am trying to form a mysql query where I want to concat all the previous values until the current row -1 . For example

select * from a;
 ------ 
| id   |
 ------ 
|    1 |
|    3 |
|    4 |
 ------ 

Desired o/p

 ------ ============
| id   |concat_prev_to_cur
 ------ ============
|    1 |null
|    3 |1
|    4 |1,3
 ------ ============

Can this be achieved with using SELECT only

Tried this but this doesn't work

with recursive b as (select id from a union all select concat(a.id,',',b.id) from b join a on a.id=b.id) select * from b;

Update: This seems to be close to the desired output

With b as (Select id, row_number() Over(order by id) r from a) select c.id,group_concat(b.id) from b join b c on b.r < c.r group by c.r ;
 ------ -------------------- 
| id   | group_concat(b.id) |
 ------ -------------------- 
|    3 | 1                  |
|    4 | 1,3                |
 ------ -------------------- 

CodePudding user response:

Maybe a recursive query is not needed.

SELECT id, (
    SELECT GROUP_CONCAT(id) AS ids
    FROM a AS agg 
    WHERE agg.id < a.id
) AS ids
FROM a

db<>fiddle

  • Related