Previous rows running string value SQL

Viewed 16

I have an input table and output should show the running value for a given number of records

Input table
*************
date           runtime_secconds 
03-Mar-2022     92                  
03-Mar-2022     586                 
02-Mar-2022     106                 
01-Mar-2022     112                 

Expected Output Result
***********************
date            runtime_secconds    running_seconds_value
03-Mar-2022     92                  92,586,106,112
03-Mar-2022     586                 586,106,112
02-Mar-2022     106                 106,112
01-Mar-2022     112                 112

Note: I want to give the input number of records as input. if I say 30 records, it has to give results for the most recent 30 days records

1 Answers

Assuming you want to order the rows by date then runtime_seconds, you can use row_number() to get the order in which you want the values concatented, then use group_concat():

with u as
(select *,
row_number() over(order by date desc, runtime_seconds) rn
from table_name)
select date,
runtime_seconds,
(select group_concat(runtime_seconds)
from u t2
where t2.rn >= t1.rn) as running_seconds_value
from u t1

Fiddle

Related