根据年份范围获取记录
本文关键字:获取 记录 范围 | 更新日期: 2023-09-27 18:14:04
我想从学生表中选择一个结果-查询-如果我通过了2013年这样的任何一年,那么选择学生加入的开始日期和结束日期,或者他目前在那里在这一年之间就像任何学生的起始日期年份是2010年,结束日期年份是2013年一样我选择了2011年,然后也展示了这个学生记录。
表格结构为-
StudentID Age startDate EndDate
1 14 5/05/2013 7/05/2013
4 17 4/04/2012 8/10/2012
我正在尝试这个-
select * from tblstudent
Where DATEPART(year, StartDate) BETWEEN @year-1 AND @year
提前谢谢。
不确定我是否理解你,但这应该能完成任务:
select *
from tblStudent s
where @year >= DATEPART(year, StartDate) and @year <= DATEPART(year, EndDate)
实际上,你几乎做到了。
您只需要比较StartDate
的年份部分小于或等于@year
和EndDate
的年份部分大于或等于@year
。
试着这样做;
select *
from tblStudent
where DATEPART(year, startDate) <= @year and DATEPART(year, EndDate) >= @year
对于@year = 2013
,输出将为;
| STUDENTID | AGE | STARTDATE | ENDDATE |
------------------------------------------------------------------------------
| 1 | 14 | May, 05 2013 03:00:00+0000 | July, 05 2013 03:00:00+0000 |
此处为SQL Fiddle Demo
。