如何查看结果日期时间dateiff dateadd,但超出范围的值

时间:2015-04-01 10:49:15

标签: sql sql-server

enter image description here

我尝试现在比较日期,并从master_employee开始工作。 但我失败了......

如果在第i行写

select @date = date_start 
from Master_Employee 
where id = '2' 

它的成功。 但我希望,可以在表Master_Employee中查看所有结果。

你可以帮帮我吗? 非常感谢..

DECLARE @date DATETIME
    ,@tmpdate DATETIME
    ,@years INT
    ,@months INT
    ,@days INT

SELECT @date = date_Start
FROM Master_Employee

SELECT @tmpdate = @date

SELECT @years = DATEDIFF(yyyy, @tmpdate, GETDATE()) - CASE 
        WHEN (MONTH(@date) > MONTH(GETDATE()))
            OR (
                MONTH(@date) = MONTH(GETDATE())
                AND DAY(@date) > DAY(GETDATE())
                )
            THEN 1
        ELSE 0
        END

SELECT @tmpdate = DATEADD(yyyy, @years, @tmpdate)

SELECT @months = DATEDIFF(mm, @tmpdate, GETDATE()) - CASE 
        WHEN DAY(@date) > DAY(GETDATE())
            THEN 1
        ELSE 0
        END

SELECT @tmpdate = DATEADD(mm, @months, @tmpdate)

SELECT @days = DATEDIFF(dd, @tmpdate, GETDATE())

SELECT @years AS Years
    ,@months AS Months
    ,@days AS Dayss
    ,GETDATE() AS Date_Now

1 个答案:

答案 0 :(得分:1)

这将为您提供所有员工总共过去的天数,月数,年数,据我所知,这就是您要做的事情。

DECLARE @Today as datetime = CONVERT(Date,GETDATE())

SELECT  SUM(DATEDIFF(day,ISNULL(convert(datetime,@date),Today),@Today)) [Days]
    ,SUM(DATEDIFF(MONTH,ISNULL(convert(datetime,@date),Today),@Today)) [Months]
    ,SUM(DATEDIFF(Year,ISNULL(convert(datetime,@date),Today(,@Today)) [Years]
FROM Master_Employee

原因

SELECT @date = date_Start
FROM Master_Employee

失败是因为您尝试将所有开始日期分配给同一个变量。

如果您想为每位员工分别行,请尝试:

DECLARE @Today as datetime = CONVERT(Date,GETDATE())

SELECT  Id
    ,SUM(DATEDIFF(day,ISNULL(convert(datetime,@date),Today),@Today)) [Days]
    ,SUM(DATEDIFF(MONTH,ISNULL(convert(datetime,@date),Today),@Today)) [Months]
    ,SUM(DATEDIFF(Year,ISNULL(convert(datetime,@date),Today),@Today)) [Years]
FROM Master_Employee
GROUP BY ID

小心,月份和年份可能会产生误导,如果此人开始12/31/14并且您在1/1/15上进行了此操作,则会看到1天,1个月,1年。你可能最好只使用几天,并计算自己的数学时间... ...