Adding multiple values in one column comma separated

ぃ、小莉子 提交于 2019-12-11 06:56:41

问题


If I have a CLOB field that contains multiple values separated by commas, and need to total them to get a final output, how can I achieve that in SQL Developer?

Example table:

STOCK | COST

ABCDE | 258.40,299.50
FGHIJ | 100.50,70.50,95.30

I would like to be able to select the total for each row.

For ABCDE looking to select a total of 557.90

For FGHIJ looking to select a total of 266.30


回答1:


If you have Oracle 12, you can use LATERAL:

select t.stock, sum(to_number(p.cst,'9999999.9999')) total
 from table_name t,
 lateral (select regexp_substr(t.cost,'[^,]+', 1, level) cst from dual
          connect by regexp_substr(t.cost, '[^,]+', 1, level) is not null) p
group by t.stock          

Otherwise:

select stock, sum(cst) total
 from (
        select stock,to_number(column_value,'9999999.9999') cst
       from  table_name t, xmltable(('"'|| REPLACE(t.cost, ',', '","')|| '"'))        
      ) p
group by stock          



回答2:


Here's a way using a CTE (Common Table Expression) with a regex that handles NULL list elements (or explicitly ignore them in the query, SUM ignores them at any rate):

SQL> -- First build the base table.
SQL> with tbl(stk, cst) as (
     select 'ABCDE', ',258.40,299.50'       from dual union
     select 'FGHIJ', '100.50,70.50,,,95.30' from dual
   ),
   -- Turn the list into a table using the comma as the delimiter. Think of it
   -- like a temp table in memory. This regex format handles NULL list elements.
   example_tbl(stock, cost) as (
     select stk, regexp_substr(cst, '(.*?)(,|$)', 1, level, NULL, 1)
     from tbl
     connect by regexp_substr(cst, '(.*?)(,|$)', 1, level) is not null
     group by stk, level, cst
   )
   -- select * from example_tbl;
   SELECT stock, to_char(sum(cost), '9990.99') Total
   from example_tbl
   group by stock;

STOCK TOTAL
----- --------
ABCDE   557.90
FGHIJ   266.30

SQL>


来源:https://stackoverflow.com/questions/38226836/adding-multiple-values-in-one-column-comma-separated

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!