Explain Codes LogoExplain Codes Logo

How to get calendar Quarter from a date in TSQL

sql
prompt-engineering
join
cte
Anton ShumikhinbyAnton Shumikhin·Dec 27, 2024
TLDR

To quickly get the quarter from a date, use the TSQL DATEPART function:

SELECT DATEPART(QUARTER, @YourDate) AS Quarter;

Substitute @YourDate with your actual date. The output will be a value from 1 to 4, representing the calendar quarters from Q1 to Q4.

Going beyond quarters: Including the year

Want the full fiscal context? Extend the quarter with its year for a YYYY-QX format:

SELECT CAST(YEAR(@YourDate) AS VARCHAR(4)) + '-Q' + CAST(DATEPART(QUARTER, @YourDate) AS VARCHAR(1)) AS YearQuarter;

The secret sauce? Concatenation, using +. Just don't spill it on your keyboard. 🤭

Tackling VARCHAR dates

Life isn't always dates and roses; sometimes you have to tackle VARCHAR dates. Cast them to a DATETIME:

SELECT DATEPART(QUARTER, CAST(@YourDateString AS DATETIME)) AS Quarter;

This avoids tantrums from SQL Server. No more tears, promise.

Descriptive quarter naming

Say it loud and clear with DATENAME. Get the English name for the quarter, perfect for report headers:

SELECT 'The ' + DATENAME(QUARTER, @YourDate) + ' Quarter' AS VerboseQuarter;

Because "Third Quarter" sounds so much more impressive than just "3".

Advanced crafting: Manual quarter calculation

Stuck in a DATEPART desert? Calculate the quarter manually:

SELECT CEILING(MONTH(@YourDate) / 3.0) AS Quarter;

Getting quarters from inactive DATEPART? That's some McGyver stuff!

Common Table Expression (CTE) for the win

In complex scenarios or when quarters don't follow the calendar, a CTE with explicit mappings is a great friend:

WITH QuarterMapping AS ( SELECT 1 AS Month, 'Q1' AS Quarter UNION ALL SELECT 2, 'Q1' UNION ALL SELECT 3, 'Q1' UNION ALL SELECT 4, 'Q2' UNION ALL -- Follow the breadcrumbs for the rest of the mappings ) SELECT m.Quarter FROM YourDateTable d JOIN QuarterMapping m ON m.Month = MONTH(d.DateColumn);

Who knew CTE could be this cool? (Well, I did. 😉)

Slicing and dicing formats

Need a customized quarter format? Express your creative side with concatenation and CONVERT:

SELECT 'Q' + CONVERT(CHAR(1), DATEPART(QUARTER, @YourDate)) + ' - ' + CONVERT(CHAR(4), YEAR(@YourDate)) AS CustomQuarterFormat;

You can't spell Queen without 'Q'! 🎤