0

在 TABLE_A 中,每个 ID 都有一个最小 SDT 和最大 EDT。

示例:对于 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 值之间。

示例小提琴

表_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
4

2 回答 2

1

您可以使用 group by 来获取最小值/最大值,并使用相关的子查询来关联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

于 2013-10-03T22:02:45.680 回答
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
);

编辑/更正:
此解决方案仅适用于您匹配 table_a 中的各个行,而不是 MIN/MAX 分组。我之前忽略了 table_a 的 MIN/MAX 分组要求。

以下使用两个没有 GROUP BY 的 EXISTS 查询并返回正确的结果:

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
));
于 2013-10-03T22:15:21.233 回答