计算列逗号分隔值的oracle

时间:2019-10-14 18:23:34

标签: oracle oracle12c

是否可以对oracle数据库表中的逗号分隔值进行计数和分组?这是一个表数据示例:

id | user | title | 
1  | foo  | a,b,c |
2  | bar  | a,d   |
3  | tee  | b     |

预期结果将是:

title | count
a     | 2
b     | 2
c     | 1
d     | 1

我想像这样使用concat:

SELECT a.title FROM Account a WHERE concat(',', a.title, ',') LIKE 'a' OR concat(',', a.title, ',') LIKE 'b' ... GROUP BY a.title?

但是我得到invalid number of arguments的concat。标题值是预定义的,因此我不在乎是否必须在查询中列出所有这些值。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

将标题拆分为行并计数。

<android.support.design.widget.FloatingActionButton
   android:src="@drawable/ic_add_white_24dp"
   android:id="@+id/addToDoItemFAB"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_margin="16dp"
   android:layout_gravity="bottom|end"/>

如果标题不是那么简单,则在第7行中修改SQL> with test (id, title) as 2 (select 1, 'a,b,c' from dual union all 3 select 2, 'a,d' from dual union all 4 select 3, 'b' from dual 5 ), 6 temp as 7 (select regexp_substr(title, '[^,]', 1, column_value) val 8 from test cross join table(cast(multiset(select level from dual 9 connect by level <= regexp_count(title, ',') + 1 10 ) as sys.odcinumberlist)) 11 ) 12 select val as title, 13 count(*) 14 From temp 15 group by val 16 order by val; TITLE COUNT(*) -------------------- ---------- a 2 b 2 c 1 d 1 SQL> (添加REGEXP_SUBSTR符号),例如

+

答案 1 :(得分:1)

这使用简单的字符串函数和递归子查询分解,并且可能比使用正则表达式和相关联接更快:

Oracle设置

CREATE TABLE account ( id, "user", title ) AS
  SELECT 1, 'foo', 'a,b,c' FROM DUAL UNION ALL
  SELECT 2, 'bar', 'a,d'   FROM DUAL UNION ALL
  SELECT 3, 'tee', 'b'     FROM DUAL;

查询

WITH positions ( title, start_pos, end_pos ) AS (
  SELECT title,
         1,
         INSTR( title, ',', 1 )
  FROM   account
UNION ALL
  SELECT title,
         end_pos + 1,
         INSTR( title, ',', end_pos + 1 )
  FROM   positions
  WHERE  end_pos > 0
),
items ( item ) AS (
  SELECT CASE end_pos
         WHEN 0
         THEN SUBSTR( title, start_pos )
         ELSE SUBSTR( title, start_pos, end_pos - start_pos )
         END
  FROM   positions
)
SELECT item,
       COUNT(*)
FROM   items
GROUP BY item
ORDER BY item;

输出

ITEM | COUNT(*)
:--- | -------:
a    |        2
b    |        2
c    |        1
d    |        1

db <>提琴here