sqlsql-servert-sqldatetime

Datetime function: semester, quarter


I am using these formulas on a select query, based on the [Date] field. Semester is 1 for Jan-Jun, 2 for Jul-Dec. Quarter is the 3-month version (1 for Jan-Mar etc).

case when Month([Date])>=7 then 2 else 1 end as [Semester],
ceiling((Month([Date])-1)/3)+1 as [Quarter]

These work, but I am wondering if there is a simpler/more elegant solution (although I've checked the datetime functions out).

It seems strange to me that a language with an ntile() function would not have something similar for dates.


Solution

  • DATEPART is suitable for your case.

    CASE WHEN DATEPART(quarter,[Date]) >= 3 THEN 2 ELSE 1 END as [Semester],
    DATEPART(quarter,[Date]) as [Quarter]