如果我的CLOB字段包含用逗号分隔的多个值,并且需要将它们合计以获得最终输出,那么我如何在SQL Developer中实现它?
示例表:
STOCK | COST
ABCDE | 258.40,299.50
FGHIJ | 100.50,70.50,95.30
我希望能够选择每一行的总数。
ABCDE希望选择总计557.90
对于FGHIJ来说,总共选择266.30
答案 0 :(得分:0)
如果您使用的是Oracle 12,则可以使用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
否则:
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
答案 1 :(得分:0)
这是使用CTE(公用表表达式)和处理NULL列表元素的正则表达式的方法(或在查询中显式忽略它们,SUM无论如何都忽略它们):
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>