计算由逗号分隔的不同值

时间:2021-06-21 00:50:05

标签: sql database oracle count distinct

我有一张名为 test

的表
<头>
id my_list
1 aa//11, aa//34, ab//65
2 bb//43, bb//43, be//54
3
4 cc//76

我想计算 my_list 中的不同值,其中列表中的每个项目用逗号分隔。在这种情况下:

  • id=1 将有 3 个不同的值
  • id=2 将有 2 个不同的值作为 bb//43 显示两次,因此 2 个不同的值
  • id=3 将有 0 个不同的值,因为它是一个空列表
  • id=4 将有 1,因为列表中只有 1 个项目

我想在纯 SQL 中执行此操作,而不是使用自定义过程。我尝试使用下面的语句,但显示为 1。

SELECT id, COUNT(DISTINCT my_list) as my_count
FROM test;

预期结果:

<头>
id my_count
1 3
2 2
3 0
4 1

1 个答案:

答案 0 :(得分:1)

您需要将您的列表变成表格以在其中count distinct。例如,使用 json_table

<块引用>
with a(id, my_list) as (
  select 1, 'aa//11, aa//34, ab//65' from dual union all
  select 2, 'bb//43, bb//43, be//54' from dual union all
  select 3, null from dual union all
  select 4, 'cc//76' from dual
)
select
  id
  , (
      select count(distinct val)
      from json_table(
        /*Replace comma with quotes and comma: ','
          And wrap with array brackets
        */
        '[''' || regexp_replace(my_list, '\s*,\s*', ''',''') || ''']'
        , '$[*]'
        columns ( val varchar(20) path '$')
      )
    ) as cnt
from a
ID | CNT
-: | --:
 1 |   3
 2 |   2
 3 |   0
 4 |   1

db<>fiddle here