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

问题描述 投票:2回答:2

基本上尝试创建一个查询,显示当前日期即将到来的月份或年份的员工周年日期,也希望显示一列显示服务年限

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

希望在下个月或明年向员工展示周年纪念日

sql-server datediff dateadd getdate
2个回答
0
投票

以下是验证的脚本(请参阅下面的pciture),以显示下个月将有birth_date的员工

用你自己的表替换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


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 
© www.soinside.com 2019 - 2024. All rights reserved.