2013-10-03 85 views
0

在TABLE_A中,每個ID都有一個最小SDT和最大EDT。ORACLE SQL Query記錄日期位於其他表的最短和最長日期之間

例如:對於ID = 1000,這將是1/09/2013和3/10/2013。

例如:對於ID = 1001,這將是1/07/2013和3/08/2013。

預期的結果將是來自TABLE_B的所有記錄,其中來自TABLE_B的SDT落在這些最小SDT和來自TABLE_A的最大EDT值之間。

Example Fiddle

TABLE_A

ID  SDT   EDT 
------------------------------ 
1000 1/10/2013 3/10/2013 
1000 1/09/2013 3/09/2013 
1001 1/08/2013 3/08/2013 
1001 1/07/2013 3/07/2013 
1002 1/06/2013 3/06/2013 

表-B

ID  SDT 
----------------- 
1000 2/10/2013 ===> because it falls between 1/09/2013 and 3/10/2013 
1000 4/09/2013 ===> because it falls between 1/09/2013 and 3/10/2013 
1001 2/08/2013 ===> because it falls between 1/07/2013 and 3/08/2013 
1001 4/05/2013 ==> not in result because it's not between 1/07/2013 and 3/08/2013 
1002 4/06/2013 ==> also out of range, so not in results 

回答

1

可以使用組通過用於最小/最大值和一個相關子查詢,以涉及table_b

Select 
    * 
From 
    Table_b b 
Where 
    Exists (
     Select 
      'x' 
     From 
      table_a a 
     Where 
      a.id = b.id 
     group by 
      a.id 
     having 
      min(a.sdt) <= b.sdt and 
      max(a.edt) >= b.sdt 
) 

Example Fiddle

0

值得一提的是,在子查詢中使用GROUP BY將有不必要的性能開銷。

SELECT b.* 
FROM table_b b 
WHERE EXISTS (
    SELECT 1 
    FROM table_a a 
    WHERE b.sdt BETWEEN LEAST(a.sdt, e.edt) AND GREATEST(a.edt, a.sdt) 
     AND a.id = b.id 
); 

編輯/更正:
如果你對各行的表-A匹配該解決方案將只適用,而不是一個最小/最大編組。我以前忽略了table_a中的MIN/MAX分組要求。

下使用兩個EXISTS查詢,沒有GROUP BY和返回正確的結果:

SELECT b.* 
FROM table_b b 
WHERE (EXISTS (
    SELECT 1 
    FROM table_a a 
    WHERE b.sdt >= a.sdt 
    AND a.id = b.id 
) AND EXISTS (
    SELECT 1 
    FROM table_a a 
    WHERE b.sdt <= a.edt 
    AND a.id = b.id 
)); 
+0

它沒有返回正確的答案:http://www.sqlfiddle.com/#!4/a196f4/14 – Laurence

+0

啊,我第一次讀這篇文章時錯過了分組要求。你是正確的先生。 :) 如果它正在尋找BETWEEN匹配個別行,那麼我的查詢將有正確的。 – MeyerRJ

相關問題