从另一个日期表中查找最近的日期范围,并将数据连接到一个表中

时间:2018-01-29 04:37:23

标签: sql sql-server

如何从另一个日期表中找到最近的日期范围,并在共享相同ID时将数据加入一个表中?

CREATE TABLE TAB_A
    ([ID] int, [StartDate] datetime,[EndDate] datetime )
;
INSERT INTO TAB_A
    ([ID], [StartDate], [EndDate])
VALUES
    (101, '2014-03-01 00:00:00', '2014-03-02 00:00:00'),
    (102, '2014-03-03 00:00:00', '2014-03-10 00:00:00'),
    (103, '2014-03-06 00:00:00', '2014-03-11 00:00:00'),
    (104, '2014-03-01 00:00:00', '2014-03-13 00:00:00'),
    (105, '2014-03-01 00:00:00', '2014-03-20 00:00:00')
;
CREATE TABLE TAB_B
    ([ID] int, [StartDate] datetime,[EndDate] datetime )
;   
INSERT INTO TAB_B
    ([ID], [StartDate], [EndDate])
VALUES
    (101, '2014-02-29 00:00:00', '2014-03-02 00:00:00'),
    (101, '2014-03-01 00:00:00', '2014-03-05 00:00:00'),
    (102, '2014-03-03 00:00:00', '2014-03-10 00:00:00'),
    (102, '2014-04-03 00:00:00', '2014-04-30 00:00:00'),
    (102, '2014-01-03 00:00:00', '2014-02-10 00:00:00'),
    (103, '2014-03-07 00:00:00', '2014-03-10 00:00:00'),
    (103, '2014-03-11 00:00:00', '2014-03-20 00:00:00'),
    (103, '2014-03-30 00:00:00', '2014-03-31 00:00:00'),
    (104, '2014-02-29 00:00:00', '2014-03-14 00:00:00'),
    (105, '2014-03-02 00:00:00', '2014-03-19 00:00:00'),
    (105, '2014-03-01 00:00:00', '2014-03-20 00:00:00'),

结果

(T1[ID],      T1[StartDate],            T1[EndDate],      T2[ID],  T2[StartDate],        T2[EndDate])
(   101, '2014-03-01 00:00:00', '2014-03-02 00:00:00' , 101, '2014-02-29 00:00:00', '2014-03-02 00:00:00')

2 个答案:

答案 0 :(得分:0)

尝试这个:您应该使用GROUP BYMIN MAX来获得所需的输出,如下所示。您可以通过在ID子句中添加WHERE来完成单个记录,也可以通过删除WHERE子句来完成所有操作

 SELECT t1.id AS [T1ID], 
    MIN(t1.StartDate) AS [T1StartDate], 
    MIN(t1.EndDate) AS [T1EndDate], 
    MAX(t2.id) [T2ID], 
    MIN(t2.StartDate) AS [T2StartDate], 
    MIN(t2.EndDate) AS [T2EndDate]
 FROM TAB_A t1
 INNER JOIN TAB_B t2 ON t1.ID = t2.ID
 WHERE t1.id = 101
 GROUP BY t1.id --Not needed if we select `ID` by using `MIN or MAX`

答案 1 :(得分:0)

If in Table TAB_A  ID is not repeated and you are passing same ID in Where condition than you can use below query also

SELECT t1.id             AS [T1ID], 
       t1.startdate      AS [T1StartDate], 
       t1.enddate        AS [T1EndDate], 
       t2.id             [T2ID], 
       Min(t2.startdate) AS [T2StartDate], 
       Min(t2.enddate)   AS [T2EndDate] 
FROM   tab_a t1 
       INNER JOIN tab_b t2 
               ON t1.id = t2.id 
                  AND t1.id = 101 
GROUP  BY t1.id, 
          t1.startdate, 
          t1.enddate, 
          t2.id