【问题标题】:Oracle How to get the count of occurrences within a comma separated stringOracle如何获取逗号分隔字符串中的出现次数
【发布时间】:2014-06-18 22:19:38
【问题描述】:

我有一个字符串,它是存储在表中的逗号分隔值。我想要字符串中每个项目的描述和计数。所以,如果一条记录有字符串'YL',我想得到'YL Description',1。但是如果记录有'YL,YB,YB',我想得到'YL description',1 AND 'YB Description ', 2.

使用以下假表来创建数据:

create table temp1 (cd_vals varchar2(20 byte));
insert into temp1 (cd_vals) values ('YB,YL');
insert into temp1 (cd_vals) values ('YB,YL,YL,YL');
insert into temp1 (cd_vals) values ('YL');

create table temp2 (cd_val varchar2(2 byte), cd_desc varchar2(20 byte));
insert into temp2 (cd_val, cd_desc) values ('YB','YB Description');
insert into temp2 (cd_val, cd_desc) values ('YL','YL Description');

我有一个查询,它返回 table1 中的每个值、查找描述以及每个原始字符串中所有实例的计数。 (Split 可能是我们系统内部的一个函数,但它需要一个逗号分隔的字符串并返回每个条目。如果我能理解它,我应该能够在解决方案中使用它。)

使用这个查询:

SELECT t1.cd_vals
     , t2.cd_desc
     , regexp_count(t1.cd_vals, '[^,]+')
FROM temp1 t1
join temp2 t2
  on rtrim(t2.cd_val) in (select column_value from table(split(rtrim(t1.cd_vals))))
order by cd_vals;

我得到以下结果:

cd_vals     cd_desc         count
YB,YL       YB Description  2
YB,YL       YL Description  2
YB,YL,YL,YL YL Description  4
YB,YL,YL,YL YB Description  4
YL          YL Description  1

但我真正想要的是:

cd_vals     cd_desc         count
YB,YL       YB Description  1
YB,YL       YL Description  1
YB,YL,YL,YL YL Description  1
YB,YL,YL,YL YB Description  3
YL          YL Description  1

如何获取最后一个计数字段,以便它显示第一个字符串中特定查找值的计数?

相关但似乎不是我正在寻找的是Count number of occurrences of keyword in comma separated column?How to get the count of occurrence from comma separated string。 (或者也许我只是看不太对。)

【问题讨论】:

    标签: sql string oracle oracle11g


    【解决方案1】:

    这是你想要的吗?

    SELECT cd_vals, cd_val, COUNT(1)
    FROM   (SELECT cd_vals,COLUMN_VALUE cd_val
            FROM   temp1 t1, table(split(rtrim(t1.cd_vals))))
    JOIN   temp2
    USING  (cd_val)
    GROUP  BY cd_vals, cd_val
    
    CD_VALS     CD_VAL COUNT(1)
    ----------- ------ --------
    YB,YL       YB            1
    YB,YL,YL,YL YL            3
    YL          YL            1
    YB,YL       YL            1
    YB,YL,YL,YL YB            1
    
    5 rows returned.
    

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 1970-01-01
      • 2012-05-19
      • 2013-08-19
      • 2023-01-03
      • 2011-09-07
      • 1970-01-01
      • 2017-10-30
      • 1970-01-01
      相关资源
      最近更新 更多