【问题标题】:Compare multiple dates on one table with multiple dates in another比较一个表中的多个日期与另一个表中的多个日期
【发布时间】:2018-02-26 18:28:42
【问题描述】:

我在 SSMS 2016 中使用 T-SQL。对于报告,我想比较两个表以查看 table2 中的日期范围是否覆盖 table1 中的日期范围,然后返回 table1 中未完全覆盖的行按表 2 中的日期范围。

table1 和 table2 中的条目数会随着时间的推移而增加。

table1                              table2

id       start date  end_date       id      start date  end date
-----------------------------       ----------------------------
1001     01/08/17    31/08/17       1001    07/07/17    02/09/17
1001     01/10/17    31/10/17       1001    01/11/17    12/12/17
1001     01/11/17    30/11/17
1001     01/01/18    05/01/18

【问题讨论】:

标签: sql-server tsql


【解决方案1】:

问题 1 查询答案

-- Does Table2 cover the date ranges in table1?  Result is by each date in Table2.
DECLARE     @t1_minStartDate    DATE,
            @t1_maxEndDate      DATE

SELECT      @t1_minStartDate    = MIN(startDate),
            @t1_maxEndDate      = MAX(endDate)
FROM        table1

SELECT      startDate AS t2_startDate,
            CASE WHEN startDate < @t1_minStartDate THEN
                'Yes'
            ELSE
                'No'
            END AS t2_startDate_covers_all,
            endDate AS t2_endDate,
            CASE WHEN startDate > @t1_maxEndDate THEN
                'Yes'
            ELSE
                'No'
            END AS t2_endDate_covers_all
FROM        table2 t2

结果:

t2_startDate    t2_startDate_covers_all t2_endDate  t2_endDate_covers_all
-------------------------------------------------------------------------
2017-07-07      Yes                     2017-09-02  No
2017-11-01      No                      2017-12-12  No



问题 2 查询答案

-- Rows in Table1 that are not fully covered by the date ranges in table2
SELECT      t1.id,
            t1.startDate,
            t1.endDate
FROM        table1 t1
WHERE       NOT EXISTS (SELECT      1
                        FROM        table2 t2
                        WHERE       t1.startDate BETWEEN t2.startDate AND t2.endDate
                                AND t1.endDate   BETWEEN t2.startDate AND t2.endDate)

结果:

id      startDate       endDate
----------------------------------
2       2017-10-01      2017-10-31
4       2018-01-01      2018-01-05

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 2011-02-04
    • 2020-10-11
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多