Reputation: 4453
I have the following query that runs in SQL Server 2014 to populate a table called DateDimension.
DECLARE @startdate datetime
DECLARE @enddate datetime
SET @startdate = '01/01/2000'
SET @enddate = '12/31/2018'
DECLARE @loopdate datetime
SET @loopdate = @startdate
WHILE @loopdate <= @enddate
BEGIN
INSERT INTO DateDimension VALUES (
Day(@loopdate),
Month(@loopdate),
Year(@loopdate),
CASE WHEN Month(@loopdate) IN (1, 2, 3) THEN 3 -- Since Financial Year starts in July, January to March is considered as Quarter 3
WHEN Month(@loopdate) IN (4, 5, 6) THEN 4
WHEN Month(@loopdate) IN (7, 8, 9) THEN 1
WHEN Month(@loopdate) IN (10, 11, 12) THEN 2
END,
@loopdate,
CONVERT(VARCHAR(10),@loopdate,111)
)
SET @loopdate = DateAdd(d, 1, @loopdate)
END
Extract of current table, after running the above query is as follows:
id Day Month Year quarter date datevarchar
1 1 1 2000 3 2000-01-01 1/1/2000
2 2 1 2000 3 2000-01-02 1/2/2000
3 3 1 2000 3 2000-01-03 1/3/2000
4 4 1 2000 3 2000-01-04 1/4/2000
5 5 1 2000 3 2000-01-05 1/5/2000
I need the "quarter" column to show its values as below:
quarter
Qr 3 2000
It would be even nicer if the "quarter" column be left as-is and a new column added to show what I'm after. How can I do this?
Upvotes: 0
Views: 4168
Reputation: 2989
You will need to add the column on to the DateDimension table first before running the query. It will be a varchar(9) column.
DECLARE @startdate datetime
DECLARE @enddate datetime
SET @startdate = '01/01/2000'
SET @enddate = '12/31/2018'
DECLARE @loopdate datetime
SET @loopdate = @startdate
WHILE @loopdate <= @enddate
BEGIN
INSERT INTO DateDimension VALUES (
Day(@loopdate),
Month(@loopdate),
Year(@loopdate),
CASE WHEN Month(@loopdate) IN (1, 2, 3) THEN 3 -- Since Financial Year starts in July, January to March is considered as Quarter 3
WHEN Month(@loopdate) IN (4, 5, 6) THEN 4
WHEN Month(@loopdate) IN (7, 8, 9) THEN 1
WHEN Month(@loopdate) IN (10, 11, 12) THEN 2
END,
@loopdate,
CONVERT(VARCHAR(10),@loopdate,111),
CASE WHEN Month(@loopdate) IN (1, 2, 3) THEN 'Qr 3 ' + CONVERT(VARCHAR(4),Year(@loopdate))
WHEN Month(@loopdate) IN (4, 5, 6) THEN 'Qr 4 ' + CONVERT(VARCHAR(4),Year(@loopdate))
WHEN Month(@loopdate) IN (7, 8, 9) THEN 'Qr 1 ' + CONVERT(VARCHAR(4),Year(@loopdate))
WHEN Month(@loopdate) IN (10, 11, 12) THEN 'Qr 2 ' + CONVERT(VARCHAR(4),Year(@loopdate))
END
)
SET @loopdate = DateAdd(d, 1, @loopdate)
END
Upvotes: 1