2013-10-03 66 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

相关问题