简体   繁体   中英

SQL Server creating a flag with dates greater than one date

Hi I'm trying to create a flag in a table which involves comparing dates. I need to be able to say if the end date is greater than the commencement date but less than 30th November of the year of commencement then flag it as a Y, if else N.

I'm on SQL Server 2014. Can anyone help me please?

Thanks

You can use a case statement for this similar to what I show below, I also included the results of the query.

CREATE TABLE #Graduates
(
    ID INT IDENTITY(1,1),
    FullName VARCHAR(1000),
    StartDate DATE,
    EndDate DATE,
    CommencementDate DATE NULL
)

INSERT INTO #Graduates
    (
        FullName,
        StartDate,
        EndDate,
        CommencementDate
    )
    SELECT
        'Curly',
        '8/26/2000',
        '06/12/2004',
        '06/5/2004'
    UNION
    SELECT
        'Doug',
        '8/23/2002',
        '06/2/2006',
        '06/12/2006'
    UNION
    SELECT
        'Larry',
        '8/23/2012',
        '12/2/2016',
        '6/4/2016'
    UNION
    SELECT
        'Moe',
        '8/23/2012',
        '12/2/2016',
        NULL

SELECT
    *,
    CASE WHEN EndDate > CommencementDate AND EndDate <= '11/30/' + CONVERT(VARCHAR(4),Year(CommencementDate)) THEN 'Y'
         ELSE 'N' END AS Flag
FROM #Graduates 

DROP TABLE #Graduates

/* RESULTS

 ID FullName    StartDate   EndDate     CommencementDate    Flag
    1   Curly   2000-08-26      2004-06-12  2004-06-05          Y
    2   Doug    2002-08-23      2006-06-02  2006-06-12          N
    3   Larry   2012-08-23      2016-12-02  2016-06-04          N
    4   Moe     2012-08-23      2016-12-02  NULL                N

*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM