我一直在进行查询以识别我的数据库中的重复项,我的要求是 - 我需要为创建日期为sysdate-1或特定日期的记录标识重复项。这可行吗? 需要基于多个表中的多个列来标识重复项。对于我的例如下面,我想搜索,我想搜索创建日期为01-AUG-2017的ID的所有重复。虽然3& 6也是重复的,但它们不应该出现在我的结果中,因为创建的日期不匹配。如果我将创建的日期过滤器添加到where where条件,则查询将丢弃结果中的匹配项。
T1
ID | V1 | V2 |CreatedDate
---| --- | --- ----------
1 | A | US 01-AUG-2017
2 | B | FR 01-JAN-2017
3 | C | AU 25-SEP-2017
4 | B | FR 01-AUG-2017
5 | A | US 30-MAR-2016
6 | C | AU 14-JUN-2015
T2
ID | V3
---| ---
1 | Apple
1 | Kiwi
2 | Pear
3 | Banana
4 | Pear
5 | Apple
6 | Banana
T3
ID | V4
---| ---
1 | Spinach
1 | Beets
2 | Celery
3 | Radish
4 | Celery
5 | Spinach
6 | Celery
6 | Radish
预期产出:
1 A US Apple Spinach
5 A US Apple Spinach
2 B FR Pear Celery
4 B FR Pear Celery
我目前的查询是:
select V1, V2, V3, V4
from (select t1.id, t1.V1,t1.V2,t2.V3,t3.V4
from t1, t2, t3
where t1.id = t2.id and t1.id = t3.id
)
group by V1, V2, V3, V4
having count(*)>1`
答案 0 :(得分:0)
我正在寻找你正在寻找的答案
select id,v1,v2,v3,v4 from
(select t1b.id,t1b.v1,t1b.v2,v3,v4,count(t1b.id) over (partition by t1b.v1,t1b.v2,v3,v4) cnt
from t1 t1a,t1 t1b,t2,t3
where t1a.CreatedDate='01-AUG-2017'
and t1a.v1=t1b.v1
and t1a.v2=t1b.v2
and t1b.id=t2.id
and t1b.id=t3.id)
where cnt>1;
您必须使用self join
来满足您的要求,并且需要使用ANALYTIC
函数来复制。
答案 1 :(得分:0)
Oracle 11g R2架构设置:
CREATE TABLE T1( ID, V1, V2, CreatedDate ) AS
SELECT 1, 'A', 'US', DATE '2017-08-01' FROM DUAL UNION ALL
SELECT 2, 'B', 'FR', DATE '2017-01-01' FROM DUAL UNION ALL
SELECT 3, 'C', 'AU', DATE '2017-09-25' FROM DUAL UNION ALL
SELECT 4, 'B', 'FR', DATE '2017-08-01' FROM DUAL UNION ALL
SELECT 5, 'A', 'US', DATE '2016-03-30' FROM DUAL UNION ALL
SELECT 6, 'C', 'AU', DATE '2015-06-14' FROM DUAL;
CREATE TABLE T2( ID, V3 ) AS
SELECT 1, 'Apple' FROM DUAL UNION ALL
SELECT 1, 'Kiwi' FROM DUAL UNION ALL
SELECT 2, 'Pear' FROM DUAL UNION ALL
SELECT 3, 'Banana' FROM DUAL UNION ALL
SELECT 4, 'Pear' FROM DUAL UNION ALL
SELECT 5, 'Apple' FROM DUAL UNION ALL
SELECT 6, 'Banana' FROM DUAL;
CREATE TABLE T3( ID, V4 ) AS
SELECT 1, 'Spinach' FROM DUAL UNION ALL
SELECT 1, 'Beets' FROM DUAL UNION ALL
SELECT 2, 'Celery' FROM DUAL UNION ALL
SELECT 3, 'Radish' FROM DUAL UNION ALL
SELECT 4, 'Celery' FROM DUAL UNION ALL
SELECT 5, 'Spinach' FROM DUAL UNION ALL
SELECT 6, 'Celery' FROM DUAL UNION ALL
SELECT 6, 'Radish' FROM DUAL;
查询1 :
SELECT ID, V1, V2, V3, V4, CreatedDate
FROM (
SELECT T1.ID, V1, V2, V3, V4, CreatedDate,
COUNT(*)
OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct,
COUNT( CASE CreatedDate WHEN DATE '2017-08-01' THEN 1 END )
OVER ( PARTITION BY V1, V2, V3, V4 ) AS ct_date_match
FROM T1
INNER JOIN T2
ON ( T1.ID = T2.ID )
INNER JOIN T3
ON ( T1.ID = T3.ID )
)
WHERE ct > 1
AND ct_date_match > 0
<强> Results 强>:
| ID | V1 | V2 | V3 | V4 | CREATEDDATE |
|----|----|----|-------|---------|----------------------|
| 1 | A | US | Apple | Spinach | 2017-08-01T00:00:00Z |
| 5 | A | US | Apple | Spinach | 2016-03-30T00:00:00Z |
| 2 | B | FR | Pear | Celery | 2017-01-01T00:00:00Z |
| 4 | B | FR | Pear | Celery | 2017-08-01T00:00:00Z |