我正在使用 SQL Server 2012,并尝试创建一个将根据以下条件返回记录的视图:
- 查询需要根据日期检索最适用的记录
- 对于内部日期范围内的日期,将返回最接近 CurrentDate 的记录
- 对于内部日期范围之外的日期,将返回最接近 CurrentDate 的记录
数据库中的示例表:
Person table:
pId | Name
----------------------
01 | Person 1
02 | Person 2
----------------------
人物日期 table:
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
如果我运行这个查询并且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)
返回的记录有:
name | startdate | enddate
-------------------------------------------
Person 1 | 2016-12-03 | 2016-12-08 --> PersonDate Table row A3
Person 2 | 2016-12-01 | 2016-12-05 --> PersonDate Table row A5
-------------------------------------------
根据我试图返回的条件,两条返回的记录都不正确。我明白为什么我得到返回的记录,这是由于在我的子查询中使用 Max() 函数,但我不知道如何编写查询/子查询。
我想要返回的正确记录是(CurrentDate 为 2016-11-28):
name | startdate | enddate
-------------------------------------------
Person 1 | 2016-11-23 | 2016-12-01
Person 2 | 2016-10-10 | 2016-12-31
-------------------------------------------
When CurrentDate
是 2016 年 12 月 2 日:
name | startdate | enddate
---------------------------------------------
Person 1 | 2014-01-08 | 2018-01-08
Person 2 | 2016-12-01 | 2016-12-05
---------------------------------------------
-
PersonDate
表行 A1,因为CurrentDate
位于 A2 行和 A3 行内部日期范围之外
-
PersonDate
表行 A5,因为CurrentDate
在日期范围内
我怎样才能编写一个根据上述条件返回记录的视图?