Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get calendar Quarter from a date in TSQL

I have different dates in a column. For example:

20080102 20070821 

I want to convert these dates in Year and calendar quarter. E.g.,

Year      Quarter 2008      2008-Q1 2007      2007-Q3 

I can get the first column with:

select left(date,4) as year from table  

How can I produce the second column?

like image 536
David Avatar asked Jun 21 '12 15:06

David


People also ask

How do you define a quarter in SQL?

QUARTER() function in MySQL is used to return the quarter of the year for a given date value. It returns a number from 1 to 4. date : The date or DateTime from which we want to extract the quarter.

How do you divide a year into quarters in SQL?

CREATE TABLE Quarter(ID INT, [Desc] varchar(100), QuarterStart DATETIME, QuarterEnd DATETIME); INSERT INTO Quarter(QuarterStart, QuarterEnd, [Desc]) VALUES ('Jan 1 2012', 'Mar 31 2012', 'Q1 2012'); INSERT INTO Quarter(QuarterStart, QuarterEnd, [Desc]) VALUES ('Apr 1 2012', 'Jun 30 2012', 'Q2 2012');


1 Answers

SELECT DATEPART(QUARTER, @date) 

This returns the quarter of the @date, assuming @date is a DATETIME.

like image 100
DLeh Avatar answered Sep 25 '22 02:09

DLeh