基于组的视图,跨表存在

时间:2016-04-12 08:38:49

标签: sql oracle select sqlplus

我有两张桌子:

T1

Col1    Col2
A       1
A       2
A       2
B       2
C       3
D       4
D       4

T2

Col1    Col2
A       2
B       2
C       4

我希望根据以下内容创建两个视图:

来自t2的Col1和Col2在t1中存在一次

来自t2的Col1和Col2不止一次存在于t1中

此预期输出为

查看1

Col1    Col2
B       2

查看2

Col1    Col2
A       2

我怎样才能实现这个目标?

表脚本:

create table t1 (col1 varchar2(1), col2 varchar2(2));
create table t2 (col1 varchar2(1), col2 varchar2(2));
insert into t1 values ('A',1);
insert into t1 values ('A',2);
insert into t1 values ('A',2);
insert into t1 values ('B',2);
insert into t1 values ('C',3);
insert into t1 values ('D',4);
insert into t1 values ('D',4);
insert into t2 values ('A',2);
insert into t2 values ('B',2);
insert into t2 values ('C',4);

1 个答案:

答案 0 :(得分:2)

您可以加入t2来自t2的汇总查询,该查询会计算col1次出现次数:

CREATE VIEW view1 AS
SELECT t2.*
FROM   t2
JOIN   (SELECT   col1, col2
        FROM     t1
        GROUP BY col1
        HAVING   COUNT(*) = 1) c ON t2.col1 = c.col1 AND t2.col2 = c.col2;

CREATE VIEW view2 AS
SELECT t2.*
FROM   t2
JOIN   (SELECT   col1, col2
        FROM     t1
        GROUP BY col1
        HAVING   COUNT(*) > 1) c ON t2.col1 = c.col1 AND t2.col2 = c.col2;