【问题标题】:Adding multiple values in one column comma separated在一列中添加多个值以逗号分隔
【发布时间】:2016-07-06 14:40:29
【问题描述】:

如果我有一个包含多个以逗号分隔的值的 CLOB 字段,并且需要将它们汇总以获得最终输出,我如何在 SQL Developer 中实现?

示例表:

STOCK | COST

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

我希望能够选择每一行的总数。

对于希望选择总共 557.90 的 ABCDE

对于希望选择总共 266.30 的 FGHIJ

【问题讨论】:

  • 如果你知道SUM(cost) .. GROUP BY ...就用这个SQL Server split CSV into multiple rows的可能重复
  • 将值存储为 CSV 是非常糟糕的数据库设计。你应该改变它
  • @JuanCarlosOropeza 您认为该解决方案是否也适用于 Oracle DB?
  • 我同意 Jens 的观点。不要将逗号分隔的值存储在单个列中。阅读数据库规范化
  • @Jens 抱歉,我当时正在使用 sql server 并感到困惑。 Oracle 更简单...stackoverflow.com/questions/14328621/…

标签: sql oracle csv addition


【解决方案1】:

如果你有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          

【讨论】:

    【解决方案2】:

    这是一种使用 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>
    

    【讨论】:

      猜你喜欢
      • 2021-11-30
      • 1970-01-01
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      相关资源
      最近更新 更多