jonathana jonathana - 2 months ago 7
SQL Question

create new column to store quarter of year from existing datetime column

My table has datetime column:

DateOfDisc
.

I need to write a query that will create dynamic new column that will show the quarter of
DateOfDisc
in that format: "Q1", "Q2", "Q3", "Q4", hence:


if Month(
DateOfDisc
) is 1 or 2 or 3 than value will be Q1
if
Month(
DateOfDisc
) is 4 or 5 or 6 than value will be Q2
if
Month(
DateOfDisc
) is 7 or 8 or 9 than value will be Q3
if
Month(
DateOfDisc
) is 10 or 11 or 12 than value will be Q4


How can I achieve that?

Answer

You can directly use DATEPART() function with Quarter option to fetch Quarter to which date belongs

SELECT *, 'Q' + CAST(DATEPART(QUARTER, DateOfDisc) AS VARCHAR(1)) as Quarter
FROM TableName