我在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
问题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