计算 Oracle 中所有列的逗号分隔值 SQL

Count comma separated values of all columns in Oracle SQL

我已经回答了很多问题,但找不到我要找的东西。 假设我有一个 table 如下:

Col1        Col2        Col3
1,2,3       2,3,4,5,1   5,6

我需要使用 select 语句得到如下结果:

Col1        Col2        Col3
1,2,3       2,3,4,5,1   5,6
3           5           2

请注意,添加的第三列是逗号分隔值的计数。 查找单个列的计数很简单,但这似乎很难,如果不是不可能的话。 提前致谢。

select
col1,
regexp_count(col1, ',') + 1 as col1count,
col2,
regexp_count(col2, ',') + 1 as col2count,
col3,
regexp_count(col3, ',') + 1 as col3count
from t

FIDDLE

FIDDLE2

Finding the count for a single column is simple, but this seems difficult if not impossible.

所以您不用手动查找每一列?你想要动态的。

这个设计实际上是有缺陷的,因为它违反了规范化。但是如果你愿意坚持下去,那么你可以在 PL/SQL 中使用 REGEXP_COUNT.

有点像,

SQL> CREATE TABLE t AS
  2  SELECT '1,2,3' Col1,
  3    '2,3,4,5,1' Col2,
  4    '5,6' Col3
  5  FROM dual;

Table created.

SQL>
SQL> DECLARE
  2    cnt NUMBER;
  3  BEGIN
  4    FOR i IN
  5    (SELECT column_name FROM user_tab_columns WHERE table_name='T'
  6    )
  7    LOOP
  8      EXECUTE IMMEDIATE 'select regexp_count('||i.column_name||', '','') + 1 from t' INTO cnt;
  9      dbms_output.put_line(i.column_name||' has cnt ='||cnt);
 10    END LOOP;
 11  END;
 12  /
COL3 has cnt =2
COL2 has cnt =5
COL1 has cnt =3

PL/SQL procedure successfully completed.

SQL>

很可能,SQL本身会有一个XML的解决方案,不用PL/SQL

在SQL-

SQL> WITH DATA AS
  2    ( SELECT '1,2,3' Col1, '2,3,4,5,1' Col2, '5,6' Col3 FROM dual
  3    )
  4  SELECT regexp_count(col1, ',') + 1 cnt1,
  5    regexp_count(col2, ',')      + 1 cnt2,
  6    regexp_count(col3, ',')      + 1 cnt3
  7  FROM t;

      CNT1       CNT2       CNT3
---------- ---------- ----------
         3          5          2

SQL>

Count the number of elements in a comma separated string in Oracle an easy way to do this is to count the number of commas然后加1

您只需要将结果合并到您的原始数据上。所以,这样做:

SQL> with the_data (col1, col2, col3) as (
  2  select '1,2,3', '2,3,4,5,1', '5,6' from dual
  3         )
  4  select a.*
  5    from the_data a
  6   union all
  7  select to_char(regexp_count(col1, ',') + 1)
  8       , to_char(regexp_count(col2, ',') + 1)
  9       , to_char(regexp_count(col3, ',') + 1)
 10    from the_data;

COL1  COL2      COL
----- --------- ---
1,2,3 2,3,4,5,1 5,6
3     5         2

您需要将结果转换为字符,因为您要将字符与数字并集,Oracle 会抱怨。

值得注意的是,以这种方式存储数据违反了第一范式。这使得操纵变得更加困难,并且几乎不可能约束其正确。值得考虑规范化您的数据模型以简化此查询和其他查询。