简体   繁体   中英

How do I populate my Date Dimension Table in SQL Server so as to get a column with this specific value?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM