Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
149 views
in Technique[技术] by (71.8m points)

sql - Splitting strings and aggregating data into existing rows or new rows

I have to query a SQL table that looks something like:

name(varchar)         | amount(double)
_________________________________________
mark, tom, & phil     |  200.
mark                  |  100.
phil                  |  50.

and I need to transform it into this:

name(varchar)         | amount(double)
_________________________________________
mark                  |  300.
phil                  |  250.
tom                   |  200.

Where I am adding the combination amount between three people to any entries already for a person in the table, and if they are not in the table, create a new entry for the person with the combination value.

I do not own the original data source table, so cannot change the design of it.

I tried searching for a similar case here on stack overflow, but could not find something like this.

question from:https://stackoverflow.com/questions/65892207/splitting-strings-and-aggregating-data-into-existing-rows-or-new-rows

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Comments explained it; see if such a query helps.

SQL> set define off;
SQL> with
  2  test (name, amount) as
  3    -- sample data
  4    (select 'mark, tom, & phil', 200 from dual union all
  5     select 'mark'             , 100 from dual union all
  6     select 'phil'             ,  50 from dual
  7    ),
  8  temp as
  9    -- split NAME to rows
 10    (select regexp_substr(name, 'w+', 1, column_value) name, amount
 11     from test cross join
 12          table(cast(multiset(select level from dual
 13                              connect by level <= regexp_count(name, ',') + 1
 14                             ) as sys.odcinumberlist))
 15    )
 16  select name, sum(amount)
 17  from temp
 18  group by name;

NAME       SUM(AMOUNT)
---------- -----------
tom                200
phil               250
mark               300

SQL>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...