简体   繁体   中英

Oracle SQL - Add numbers separated by delimiter, columnwise

I have multiple rows with values like

a_b_c_d_e_f and x_y_z_m_n_o

and I need a SQL query with a result like a+x_b+y_c+z_d+m.......

Sample data as requested样本数据

What I am willing to do is aggregate it at Datetime..aggregating Total is simple, but how can I do that for the last column, thanks.

Expected Result在此处输入图像描述

Here's one option; read comments within code. I didn't feel like typing too much so two dates will have to do.

Sample data (you already have that & don't type it. Code you need begins at line #10):

SQL> with
  2  -- sample data
  3  test (datum, total, col) as
  4    (select date '2020-07-20', 100, '10,0,20,30,0' from dual union all
  5     select date '2020-07-20', 150, '15,3,40,30,2' from dual union all
  6     --
  7     select date '2020-07-19', 200, '50,6,50,30,8' from dual union all
  8     select date '2020-07-19', 300, '20,1,40,10,2' from dual
  9    ),

Split CSV values into rows. Note the RB value which will help us sum matching values

 10  -- split comma-separated values into rows
 11  temp as
 12    (select
 13        datum,
 14        total,
 15        to_number(regexp_substr(col, '\d+', 1, column_value)) val,
 16        column_value rb
 17      from test cross join
 18        table(cast(multiset(select level from dual
 19                            connect by level <= regexp_count(col, ',') + 1
 20                           ) as sys.odcinumberlist))
 21    ),

Computing summaries is simple; nothing special about it. We'll keep the RB value as it'll be needed in the last step:

 22  -- compute summaries
 23  summary as
 24    (select datum,
 25       sum(total) total,
 26       sum(val) sumval,
 27       rb
 28     from temp
 29     group by datum, rb
 30    )

The last step. Using LISTAGG , aggregate comma-separated values back, but this time added to each other:

 31  -- final result
 32  select datum,
 33    total,
 34    listagg(sumval, ',') within group (order by rb) new_col
 35  from summary
 36  group by datum, total
 37  order by datum desc, total;

DATUM                    TOTAL NEW_COL
------------------- ---------- --------------------
20.07.2020 00:00:00        250 25,3,60,60,2
19.07.2020 00:00:00        500 70,7,90,40,10

SQL>

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