0

我需要计算从今天到员工受雇日期之间的天数(但不在乎年份)。这意味着如果一名员工在 2012 年 7 月 1 日雇用,我想得到一个结果是今天 2013 年 7 月 15 日-2013 年 7 月 1 日,即 15 天。我不需要 2012 年的雇佣年度。

我玩弄 dateadd 和 datediff 但没有得到正确的结果。

SELECT 
    Co Employee, 
    LastName, 
    FirstName, 
    dateadd(dd,  DATEDIFF(dd,CURRENT_TIMESTAMP,0),HireDate)
FROM dbo.PREH
4

3 回答 3

2

You could use modulus division:

SELECT DATEDIFF(DAY,'20120101',GETDATE())%365

The downside is that you're treating leap year the same as every other year, which you could handle with case logic.

In your code:

SELECT 
    Co Employee, 
    LastName, 
    FirstName, 
    DATEDIFF(DAY,HireDate,GETDATE())%365 AS DaysThisYear
FROM dbo.PREH
于 2013-07-15T18:56:12.473 回答
1

这可能有点蛮力,但它似乎有效。这个想法是给受雇日期增加几年,然后对照当前日期检查。当它更大时,使用更少的年份:

select (case when DATEADD(year, datediff(year, hiredate, getdate()), hiredate) < GETDATE()
             then DATEDIFF(dd, DATEADD(year, datediff(year, hiredate, getdate()), hiredate), getdate())
             else DATEDIFF(dd, DATEADD(year, datediff(year, hiredate, getdate()) - 1, hiredate), getdate())
        end)
from preh;

问题是datediff()withyear返回跨越年份边界的次数,而不是作为跨度的两个日期之间的年数。所以,2012-12-30 和 2013-01-01 之间有一年,2012-01-01 和 2013-12-31 之间有一年。

于 2013-07-15T18:59:42.907 回答
0

It sounds like you're dropping the year just as part of formatting the output. Formatting shouldn't affect the underlying data though. The last element of your tuple should be:

datediff(day, HireDate, getdate())

That way you can do arithmetic on the data, and save the formatting for downstream, when it's needed.

于 2013-07-15T18:57:33.830 回答