Get the quarter of a given date in datetime format
In SQL Server you can get the quarter of a year by using the datepart function. This will return 1/1/year, 4/1/year, 7/1/year or 10/1/year depending on the date you entered.
Sometimes, it is necessary to get the quarter of a given date in datetime format. Here is a simple scalar function how to do it:
CREATE FUNCTION GetQuarter (@date DATETIME)
RETURNS DATETIME
AS
BEGIN
RETURN CONVERT(DATETIME, CONVERT(CHAR(8),
DATEPART(YEAR, @date) * 10000 +
( DATEPART(QUARTER, @date) * 3 - 2) * 100 +
1),
112)
END
Use the function like this:
SELECT dbo.GetQuarter(dateColumn) AS Quarter FROM myTable
1 comments:
Here is another way to do that without having to create a UDF:
--1st day of Quarter
DATEADD(qq,DATEDIFF(qq,0,@date),0)
I use this type of function all the time to find other significant dates:
--1st day of Month
DATEADD(mm,DATEDIFF(mm,0,@date),0)
--1st day of Year
DATEADD(yy,DATEDIFF(yy,0,@date),0)
Post a Comment