从另一个表中获取以前的日期

时间:2017-07-12 07:38:11

标签: sql oracle

我有2张桌子。 1表看起来像这样 (值存储为DD-MM-YYYY)

表A:

CustID | StartDate 
1      | 20-1-2016
2      | 25-1-2016
2      | 17-6-2016

表B:

CustID  |  StartDate  |  EndDate
1       |  1-1-2016   |  15-1-2016
1       |  20-1-2016  |  1-4-2016
2       |  1-1-2015   |  1-6-2015
2       |  5-8-2015   |  31-12-2015
2       |  25-1-2016  |  31-5-2016
2       |  17-6-2016  |  31-12-2016

所以我想要的是获得表A中的所有数据。并在表B中找到上一个日期。因此在表B中,在表A的startdate之前的每个日期范围中,我想要最高的EndDate。

所以它看起来像这样:

表决赛:

CustID | TableA.StartDate |  TableB.EndDate (as Previous_date)
1      | 20-1-2016        |  15-1-2016
2      | 25-1-2016        |  31-12-2015
2      | 17-6-2016        |  31-5-2016

我希望这是足够的信息来获得一些帮助。如果您需要更多,请告诉我。

2 个答案:

答案 0 :(得分:0)

我的解决方案是这样的:
如果你想从表B中选择其他列,它会工作。

SELECT A.id
      ,A.startdate
      ,B.enddate
   FROM tblA A
  INNER JOIN tblB B
     ON A.id = B.id
    AND B.startdate = (
                   SELECT TOP 1 startdate
                     FROM tblB subB
                    WHERE A.id = subB.ID
                      AND subB.startdate < A.startdate
                    ORDER BY startdate desc         
                      )

如果你想重现结果,这里有一个rextester链接: http://rextester.com/SGNX33699

答案 1 :(得分:0)

我会使用LAG分析函数来执行此操作:

WITH a AS (SELECT 1 custid, to_date('20/01/2016', 'dd/mm/yyyy') startdate FROM dual UNION ALL
           SELECT 2 custid, to_date('25/01/2016', 'dd/mm/yyyy') startdate FROM dual UNION ALL
           SELECT 2 custid, to_date('17/06/2016', 'dd/mm/yyyy') startdate FROM dual),
     b AS (SELECT 1 custid, to_date('01/01/2016', 'dd/mm/yyyy') startdate, to_date('15/01/2016', 'dd/mm/yyyy') enddate FROM dual UNION ALL
           SELECT 1 custid, to_date('20/01/2016', 'dd/mm/yyyy') startdate, to_date('01/04/2016', 'dd/mm/yyyy') enddate FROM dual UNION ALL
           SELECT 2 custid, to_date('01/01/2015', 'dd/mm/yyyy') startdate, to_date('01/06/2016', 'dd/mm/yyyy') enddate FROM dual UNION ALL
           SELECT 2 custid, to_date('05/08/2015', 'dd/mm/yyyy') startdate, to_date('31/12/2015', 'dd/mm/yyyy') enddate FROM dual UNION ALL
           SELECT 2 custid, to_date('25/01/2016', 'dd/mm/yyyy') startdate, to_date('31/05/2016', 'dd/mm/yyyy') enddate FROM dual UNION ALL
           SELECT 2 custid, to_date('17/06/2016', 'dd/mm/yyyy') startdate, to_date('31/12/2016', 'dd/mm/yyyy') enddate FROM dual),
    b2 AS (SELECT custid,
                  startdate,
                  enddate,
                  lag(enddate) OVER (PARTITION BY custid ORDER BY startdate) prev_enddate
           FROM   b)
SELECT a.custid,
       a.startdate,
       b2.prev_enddate
FROM   a
       INNER JOIN b2 ON a.startdate = b2.startdate;

    CUSTID STARTDATE   PREV_ENDDATE
---------- ----------- ------------
         1 20/01/2016  15/01/2016
         2 25/01/2016  31/12/2015
         2 17/06/2016  31/05/2016