Skip to content
Advertisement

Extracting Dates based on Months

I have a table in an MSSQL database that lists when students start a programme. The academic year runs from August to July.

Where a student starts on 01 Sep 2019 I want to show that they started in 19/20 If they start on 06 May 2020 I want to show they started in 19/20 If they start on 05 Aug 2020 I want to show they start in 20/21

I have tried to do this as a Case statement

SELECT 
   LEARNERID
  ,(
    CASE 
      WHEN datepart(MM, LEARNSTARTDATE) BETWEEN 8 AND 12
        THEN datepart(YY, LEARNSTARTDATE)
      END
    ) AS StartYear
  ,(
    CASE 
      WHEN datepart(MM, LEARNSTARTDATE) BETWEEN 1 AND 7
        THEN datepart(YY, LEARNSTARTDATE)
      END
    ) AS EndYear
FROM ILR

This is not working for me

Any help with this would be appreciated. Thanks

Advertisement

Answer

I would offset the date by 6 month, and format it as follows:

format(dateadd(month, -6, learnstartdate), 'yy')
    + '/'
    + format(dateadd(month, 6, learnstartdate), 'yy')

Demo on DB Fiddle:

select  
    learnstartdate, 
    format(dateadd(month, -6, learnstartdate), 'yy')
        + '/'
        + format(dateadd(month, 6, learnstartdate), 'yy') scholar_year
from (values('2019-09-01'), ('2020-05-06'), ('2020-08-05')) t(learnstartdate)
GO
learnstartdate | scholar_year
:------------- | :-----------
2019-09-01     | 19/20       
2020-05-06     | 19/20       
2020-08-05     | 20/21       
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement