输入数据
Some_Table
ST_Field1 ST_Field2
Apple A
Apple A
Apple D
Orange D
Orange E
Orange Z
Pear D
Pear G
Pear C
Reference_Table
RT_Field1 RT_Field2
1 A
1 B
1 C
2 D
2 E
2 F
3 G
预期结果:
ST_Field1 ST_Field2
Orange D
Orange E
CREATE TABLE SOME_TABLE
( ST_Field1 VARCHAR(100),
ST_Field2 VARCHAR(100)
);
INSERT INTO SOME_TABLE VALUES ('Apple','A');
INSERT INTO SOME_TABLE VALUES ('Apple','A');
INSERT INTO SOME_TABLE VALUES ('Apple','D');
INSERT INTO SOME_TABLE VALUES ('Orange','D');
INSERT INTO SOME_TABLE VALUES ('Orange','E');
INSERT INTO SOME_TABLE VALUES ('Orange','Z');
INSERT INTO SOME_TABLE VALUES ('Pear','D');
INSERT INTO SOME_TABLE VALUES ('Pear','G');
INSERT INTO SOME_TABLE VALUES ('Pear','C');
CREATE TABLE REFERENCE_TABLE
( RT_Field1 INTEGER,
RT_Field2 VARCHAR(100)
);
INSERT INTO REFERENCE_TABLE VALUES (1,'A');
INSERT INTO REFERENCE_TABLE VALUES (1,'B');
INSERT INTO REFERENCE_TABLE VALUES (1,'C');
INSERT INTO REFERENCE_TABLE VALUES (2,'D');
INSERT INTO REFERENCE_TABLE VALUES (2,'E');
INSERT INTO REFERENCE_TABLE VALUES (2,'F');
INSERT INTO REFERENCE_TABLE VALUES (3,'G');
可以假定RT_Field2是唯一的。
我希望从Some_Table获取记录,这些记录具有RT_Field2的多个不同值,并按RT_Field1和ST_Field1分组。
因此,从参考表{A,B,C}中进行分组。我想查看给定的ST_Field1是否看到{A,B}; {B,c},{A,C}。我没有,我看到A和C,但是在Apple和Pear之间。
唯一的成功是Orange,我在这里寻找{D,E},{D,F}或{E,F},并找到Orange的D和E。
我有:
WITH DUP_VALUES_RTF2 AS
( SELECT *
FROM (SELECT DST.ST_Field1,
DST.ST_Field2,
COUNT(1) OVER (PARTITION BY RT.RT_Field1) cnt_RTF1
FROM (SELECT DISTINCT
ST_Field1,
ST_Field2
FROM Some_Table
) DST
INNER
JOIN REFERENCE_TABLE RT
ON DST.ST_Field2 = RT.RT_Field2
) TMP
WHERE cnt_RTF1 > 1
)
SELECT *
FROM SOME_TABLE ST
WHERE EXISTS
( SELECT 1
FROM DUP_VALUES_RTF2 DVR
WHERE ST.ST_Field1 = DVR.ST_Field1
AND ST.ST_Field2 = DVR.ST_Field2
);
什至没有真正接近,因为它根本无法正确处理分组并且非常丑陋。也许下午5点以后我就快要死了。
答案 0 :(得分:1)
您可以尝试以下类似操作
; with distinctSet as
(select distinct s.*,RT_Field1 from SOME_TABLE s join REFERENCE_TABLE r on s.ST_Field2=r.RT_Field2
)
,
uniqueSet as
(
select RT_Field1,ST_Field1
from distinctSet
group by RT_Field1,ST_Field1
having count(1)>1
),
resultSet as
(
select
distinct
s.*
from SOME_TABLE s
join REFERENCE_TABLE r
on s.ST_Field2=r.RT_Field2
join uniqueSet u
on u.RT_Field1=r.RT_Field1
and u.ST_Field1=s.ST_Field1
)
select * from resultSet
答案 1 :(得分:1)
如果我正确理解这一点,则想匹配st_field1
和rt_field1
,在rt_field2
中查找重复项。您可以为此使用窗口功能:
select s.*
from (select s.*, rt.rt_field1, rt.rt_field2,
min(rt.rt_field2) over (partition by s.st_field1, r.rt_field1) as min_rt2,
max(rt.rt_field2) over (partition by s.st_field1, r.rt_field1) as max_rt2
from sometable s join
reference_table r
on s.st_field2 = r.rt_field2
) s
where min_rt2 <> max_rt2;