Below is the given table data:
CREATE TABLE #tbl_period (
period_no INT,
period_from SMALLDATETIME,
period_to SMALLDATETIME
)
INSERT INTO #tbl_period (period_no, period_from, period_to)
VALUES (1, '2004-11-01 00:00:00', '2005-10-31 00:00:00')
INSERT INTO #tbl_period (period_no, period_from, period_to)
VALUES (2, '2005-11-01 00:00:00', '2006-10-31 00:00:00')
INSERT INTO #tbl_period (period_no, period_from, period_to)
VALUES (3, '2006-11-01 00:00:00', '2007-10-31 00:00:00')
INSERT INTO #tbl_period (period_no, period_from, period_to)
VALUES (4, '2007-11-01 00:00:00', '2008-10-31 00:00:00')
INSERT INTO #tbl_period (period_no, period_from, period_to)
VALUES (5, '2008-11-01 00:00:00', '2009-10-31 00:00:00')
INSERT INTO #tbl_period (period_no, period_from, period_to)
VALUES (6, '2009-11-01 00:00:00', '2010-10-31 00:00:00')
INSERT INTO #tbl_period (period_no, period_from, period_to)
VALUES (7, '2010-11-01 00:00:00', '2011-10-31 00:00:00')
SELECT * FROM #tbl_period
DROP TABLE #tbl_period
Now, The goal is to retrieve the period_no which having 2 given dates who will be compared to period_from and period_to columns.
Example1:
date1 = '2010-11-01 00:00:00'
date2 = '2011-10-31 00:00:00'
This will return 7 as the period_no
Example2:
date1 = '2005-11-01 00:00:00'
date2 = '2007-10-31 00:00:00'
It should not return a period_no because the date range given does not in the range of period_from and period_to column in a row. Overlap dates is not allowed.
The rule is to retrieve a period_no if the 2 given date will have a match or be in a range of period_from and period_to column in a row.
How to do this query in T-SQL?
Thanks in advance!
I reckon this is what you’re after:
Tests:
returns
and
returns