简体   繁体   English

根据年份范围获取记录

[英]Get Record according to year range

I want to select a result from student table- query - if I pass any year like 2013 then select the students join start date and end date or he is currently there in between these year like if any student start date year is 2010 and end date year is 2013 and I select 2011 year then show this student record also . 我想从学生表查询中选择一个结果-如果我通过了像2013这样的年份,则选择学生加入的开始日期和结束日期,或者他目前在这些年份之间,例如如果任何学生的开始日期是2010年和结束日期年是2013年,我选择2011年,然后也显示该学生记录。

Table structure is- 表结构是-

StudentID   Age startDate   EndDate

1           14  5/05/2013   7/05/2013   
4           17  4/04/2012   8/10/2012

and I'm trying this- 我正在尝试-

select * from tblstudent 
Where  DATEPART(year, StartDate) BETWEEN @year-1 AND @year

Thanks in advance. 提前致谢。

Not sure if I understood you, but this should do the job: 不知道我是否了解您,但这应该可以完成工作:

select *
from tblStudent s
where @year >= DATEPART(year, StartDate) and @year <= DATEPART(year, EndDate)

Actually , you almost there. 实际上 ,您快到了。

You just need to compare year part of your StartDate is smaller or equal to your @year and year part of your EndDate is bigger or equal to your @year . 您只需要比较StartDate年份部分小于或等于@year EndDate年份部分大于或等于@year

Try like this; 这样尝试;

select *
from tblStudent
where DATEPART(year, startDate) <= @year and DATEPART(year, EndDate) >= @year

For @year = 2013 , output will be; 对于@year = 2013 ,输出将为;

| STUDENTID | AGE |                  STARTDATE |                     ENDDATE |
------------------------------------------------------------------------------
|         1 |  14 | May, 05 2013 03:00:00+0000 | July, 05 2013 03:00:00+0000 |

Here SQL Fiddle Demo . 这里是SQL Fiddle Demo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM