如何从逗号分隔的字符串中获取出现次数

时间:2014-02-17 15:10:39

标签: sql oracle

我在Oracle 8i

中有两个表格

对于T1表中的每个col1,我们需要找出T2表中出现的次数(用于匹配col3)。

问题

使用单个查询在Oracle中实现此目的的最佳方法是什么(不创建临时表)?

Fiddle

预期结果

'C1' - 10 - 1

'C1' - 8 - 1

'C2' - 10 - 1

'C3' - 10 - 0

'C4' - 10 - 2

SQL

--Table 1
CREATE TABLE T1 (col1 varchar2(2), col2 varchar(8), col3 NUMBER);

INSERT INTO T1  (col1, col2, col3) VALUES  ('C1', 'john',10);
INSERT INTO T1  (col1, col2, col3) VALUES ('C1', 'nishal',8);
INSERT INTO T1  (col1, col2, col3) VALUES  ('C2', 'piers',10);
INSERT INTO T1  (col1, col2, col3) VALUES  ('C3', 'sara',10);
INSERT INTO T1  (col1, col2, col3) VALUES  ('C4', 'lijo',10);


--Table 2

CREATE TABLE T2 (col1 varchar2(2), col2 varchar(8), col3 NUMBER);

INSERT INTO T2  (col1, col2 , col3) VALUES ('R0', 'C1,C4',10);
INSERT INTO T2  (col1, col2 , col3) VALUES ('R1', 'C1',8);
INSERT INTO T2  (col1, col2 , col3) VALUES ('R2', 'C2,C4',10);

Fiddle

1 个答案:

答案 0 :(得分:2)

select  T1.col1
,       T1.col3
,       count(T2.col1)
from    T1
left join
        T2
on      T1.col3 = T2.col3
        and ',' || T2.col2 || ',' like '%,' || T1.col1 || ',%'
group by
        T1.col1
,       T1.col3

Example at SQL Fiddle.