需要使用DATEADD的帮助,仅显示当前日期之后的列日期

时间:2019-03-29 18:15:48

标签: sql sql-server date dateadd

当前正在编写查询以提取员工的周年纪念日。到目前为止,我可以将日期拉长5、10、15和25年,但我试图将日期分别拉长到当前日期之后。有任何想法吗?

SELECT
    HireDate, 
    DATEADD(year, 5, HireDate)  AS '5_Year_Anniversary',
    DATEADD(year, 10, HireDate) AS '10_Year_Anniversary',
    DATEADD(year, 15, HireDate) AS '15_Year_Anniversary',
    DATEADD(year, 25, HireDate) AS '25_Year_Anniversary'
FROM
    EMPTABLE;

2 个答案:

答案 0 :(得分:1)

SELECT
    HireDate, 
    case when DATEADD(year, 5, HireDate) >= getdate() --check to see if the anniversary is on or after the current date
         then DATEADD(year, 5, HireDate) 
         else NULL end  AS '5_Year_Anniversary' --etc, repeat for your other columns
FROM
    EMPTABLE
where DATEADD(year, 25, HireDate) >= getdate() --to filter out employees where all anniversary columns would be NULL

使用上述类似的案例声明应可行,这取决于您在员工已过周年纪念日时要为这些列显示的值。如果您希望在这些情况下使用特定的值,则可能需要cast / convert周年纪念日。

例如:

SELECT
    HireDate, 
    case when DATEADD(year, 5, HireDate) >= getdate() --check to see if the anniversary is on or after the current date
         then cast(DATEADD(year, 5, HireDate)  as varchar(20))
         else 'Already Passed' end  AS '5_Year_Anniversary' --etc, repeat for your other columns
FROM
    EMPTABLE
where DATEADD(year, 25, HireDate) >= getdate() --to filter out employees where all anniversary columns would be NULL

答案 1 :(得分:0)

比较每个周年纪念日,仅在周年纪念日在当前日期之后显示。

SELECT语句是解决方案。如果日期已过,则字段将返回NULL。

CREATE TABLE #EMPTABLE
(
    HireDate datetime
)
GO

INSERT INTO #EMPTABLE
VALUES
    ('2018-01-01'),
    ('2013-01-01'),
    ('2008-01-01'),
    ('2003-01-01'),
    ('1993-01-01')
GO


SELECT
    GETDATE() [Current Date],
    HireDate, 
    CASE WHEN ( DATEADD(year, 5, HireDate) > GETDATE() )
        THEN DATEADD(year, 5, HireDate)
        ELSE NULL
    END AS [5_Year_Anniversary],
    CASE WHEN ( DATEADD(year, 10, HireDate) > GETDATE() )
        THEN DATEADD(year, 10, HireDate)
        ELSE NULL
    END AS [10_Year_Anniversary],
    CASE WHEN ( DATEADD(year, 15, HireDate) > GETDATE() )
        THEN DATEADD(year, 15, HireDate)
        ELSE NULL
    END AS [15_Year_Anniversary],
    CASE WHEN ( DATEADD(year, 25, HireDate) > GETDATE() )
        THEN DATEADD(year, 25, HireDate)
        ELSE NULL
    END AS [25_Year_Anniversary]
FROM
    #EMPTABLE
GO