I am using SQL Server 2012, and I am trying to create a VIEW that will return records based on these conditions:
- The request should receive the most suitable record depending on the date
- For dates in the internal date range, the closest entry in CurrentDate will be returned
- For dates outside the internal date range, the closest entry in CurrentDate will be returned.
Examples of tables in the database:
Person :
pId | Name
----------------------
01 | Person 1
02 | Person 2
----------------------
PersonDate :
dId | pId | StartDate | EndDate
---------------------------------------------------
A1 | 01 | 2014-01-08 | 2018-01-08
A2 | 01 | 2016-11-23 | 2016-12-01
A3 | 01 | 2016-12-03 | 2016-12-08
A4 | 02 | 2016-10-10 | 2016-12-31
A5 | 02 | 2016-12-01 | 2016-12-05
If I run this query, and CurrentDate- 2016-11-28:
select p.name, d.startdate, d.enddate
from Person p, PersonDate d
where p.pId = d.pId
and d.StartDate = (select max(sl.StartDate)
from PersonDate sl
where d.pId = s1.pId)
Return records:
name | startdate | enddate
Person 1 | 2016-12-03 | 2016-12-08
Person 2 | 2016-12-01 | 2016-12-05
, . , , Max() , , /.
, (CurrentDate - 2016-11-28):
name | startdate | enddate
-------------------------------------------
Person 1 | 2016-11-23 | 2016-12-01
Person 2 | 2016-10-10 | 2016-12-31
-------------------------------------------
PersonDate A2, CurrentDate ( # 2)
PersonDate A4, (A5) ( № 3)
CurrentDate - 2016-12-02:
name | startdate | enddate
---------------------------------------------
Person 1 | 2014-01-08 | 2018-01-08
Person 2 | 2016-12-01 | 2016-12-05
---------------------------------------------
PersonDate A1, CurrentDate A2 A3PersonDate A5, CurrentDate
VIEW, ?