显示员工在当前日期的下个月或年份内的周年纪念日

时间:2019-04-02 16:16:19

标签: sql-server datediff dateadd getdate

基本上试图创建一个查询,该查询将显示即将到来的月份或当前日期的雇员周年纪念日,还希望显示一列显示服务年限的列

SELECT
Employee,
Hire_Date

CASE WHEN DATEADD(YY,DATEDIFF(yy,Hire_Date,GETDATE()),Hire_Date)<GETDATE() THEN DATEDIFF(yy,Hire_Date,GETDATE())
ELSE DATEDIFF(yy,Hire_Date,GETDATE())-1 END AS 'Years of service'

FROM
MyTable

希望显示下个月或下一年的周年纪念日员工

2 个答案:

答案 0 :(得分:0)

这是经过验证的脚本(请参见下面的图片),以显示下个月出生日期为员工的员工

用您自己的表替换mytable

declare @mytable as table(employe varchar(100), birth_date datetime,hire_date datetime)

insert into @mytable values
('name1','01/01/1972','01/01/2000') ,
('name2','12/02/1985','01/02/2003') ,
('name3','04/12/1990','03/04/2005') ,
('name4','05/03/1969','12/12/2005') ,
('name5','04/02/1968','12/02/2010') ,
('name6','04/04/1968','12/11/2009') ,
('name7','12/03/1978','01/01/2019') ,
('name8','01/12/2000','03/02/2018') ,
('name9','12/12/1970','05/02/2019') ,
('name10','04/04/1980','04/04/2018') 

select employe,birth_date,hire_date,
CASE WHEN DATEADD(YY,DATEDIFF(yy,Hire_Date,GETDATE()),Hire_Date)<GETDATE() THEN DATEDIFF(yy,Hire_Date,GETDATE())
ELSE DATEDIFF(yy,Hire_Date,GETDATE())-1 END AS 'Years of service'
from @mytable where (
month(getdate()) < 12 
and 
month(birth_date)=1+month(getdate()) )
or (month(getdate())=12 and month(birth_date)=1)

enter image description here

答案 1 :(得分:0)

我不太了解,但是,如果您需要知道谁在下个月或下一年做周年纪念,则应该使用DATEDIFF函数来过滤数据。

示例:

SELECT Employee, Hire_Date, DATEDIFF(year, Hire_Date, getdate()) as YearsService
FROM MyTable
-- if you need fetch to next month, you should use <= 1
WHERE DATEDIFF(month, CONCAT(YEAR(GETDATE()), '-', MONTH(Hire_Date), '-' , DAY(Hire_Date)), GETDATE()) = 1