I am using SQL Server 2014 and I have the following T-SQL query:
SELECT
[Date],
(CASE
WHEN [Date] BETWEEN '2016-07-01' AND '2017-06-30' THEN 'FY 16-17'
WHEN [Date] BETWEEN '2017-07-01' AND '2018-06-30' THEN 'FY 17-18'
WHEN [Date] BETWEEN '2018-07-01' AND '2019-06-30' THEN 'FY 18-19'
ELSE 'Not Stated'
END) AS [Period]
FROM
DateDimension
WHERE
[Date] BETWEEN '2016-07-01' AND '2019-06-30'
The output is as follows (extract):
Date Period
-----------------------
2016-07-01 FY 16-17
2016-07-02 FY 16-17
2016-07-03 FY 16-17
... ...
2017-07-01 FY 17-18
2017-07-02 FY 17-18
2017-07-03 FY 17-18
... ...
2018-07-01 FY 18-19
2018-07-02 FY 18-19
2018-07-03 FY 18-19
... ...
I want to add a new column to the output as follows:
Date Period Day
-------------------------------
2016-07-01 FY 16-17 D1
2016-07-02 FY 16-17 D2
2016-07-03 FY 16-17 D3
... ... ...
2017-07-01 FY 17-18 D1
2017-07-02 FY 17-18 D2
2017-07-03 FY 17-18 D3
... ... ...
2018-07-01 FY 18-19 D1
2018-07-02 FY 18-19 D2
2018-07-03 FY 18-19 D3
... ... ...
To note that D1
starts again at the beginning of each new financial year (that is,2016-07-01
, 2017-07-01
and 2018-07-01
).
How do I write the SQL code for this new column?
Additional note: D1
should be continuous till the end of each financial year. Example, from 2016-07-01
till 2017-06-30
, column Period
will show D1, D2, ..., D365)