sql >> Base de Datos >  >> RDS >> Sqlserver

Mostrar en qué trimestre de un año financiero se encuentra una fecha

Esto debería funcionar:-

SELECT
    MyDate,
    CASE
        WHEN MONTH(MyDate) BETWEEN 1  AND 3  THEN convert(char(4), YEAR(MyDate) - 1) + 'Q3'
        WHEN MONTH(MyDate) BETWEEN 4  AND 6  THEN convert(char(4), YEAR(MyDate) - 1) + 'Q4'
        WHEN MONTH(MyDate) BETWEEN 7  AND 9  THEN convert(char(4), YEAR(MyDate) - 0) + 'Q1'
        WHEN MONTH(MyDate) BETWEEN 10 AND 12 THEN convert(char(4), YEAR(MyDate) - 0) + 'Q2'
    END AS Quarter
FROM
    MyTable

Salida:-

MyDate        Quarter
----------    --------
2011-01-01    "2010Q3"
2011-04-01    "2010Q4"
2011-07-01    "2011Q1"
2011-10-01    "2011Q2"