I have following data in my table:
uniqueId d_date amount
1 2018-02-01 100.25
2 2019-03-01 456.5
3 2018-02-01 455
4 2019-05-01 200.48
5 2018-06-01 100
6 2019-07-01 200
7 2018-12-01 6950
8 2019-02-01 60
9 2020-01-20 100
Now when I enter start date = '2018-03-12'
then my fiscal year must start with march 2018 to feb 2019
and so on.
If i enter start date = '2019-05-12' then my fiscal year must start with May 2019 to April 2020
I have tried below query but it is not working properly and also it calculate past year which is 2017 I do not want any data from past year from my entered custom date. So if entered start date = '2018-03-12' then is must start calculation for 2018 and above years only. No past year.
Declare @startdate as date
Declare @monthDate as int
Declare @ownmonth as int
set @startdate = '2018-03-12'
set @monthDate = month(@startdate)
set @ownmonth = 1
select
year(dateadd(month, -@monthDate, d_date)) year,
sum(case when month(d_date) = case when @monthDate+1 > 12 then @ownmonth else @monthDate+1 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+2 > 12 then @ownmonth+1 else @monthDate+2 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+3 > 12 then @ownmonth+2 else @monthDate+3 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+4 > 12 then @ownmonth+3 else @monthDate+4 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+5 > 12 then @ownmonth+4 else @monthDate+5 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+6 > 12 then @ownmonth+5 else @monthDate+6 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+7 > 12 then @ownmonth+6 else @monthDate+7 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+8 > 12 then @ownmonth+7 else @monthDate+8 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+9 > 12 then @ownmonth+8 else @monthDate+9 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+10 > 12 then @ownmonth+9 else @monthDate+10 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+11 > 12 then @ownmonth+10 else @monthDate+11 End then amount end) ,
sum(case when month(d_date) = case when @monthDate+12 > 12 then @ownmonth+11 else @monthDate+12 End then amount end) ,
sum(amount) total
from mytable
group by year(dateadd(month, -@monthDate, amount))
order by year
But above query does not show proper year & month wise data
Now I want output with fiscal year calculation:
Year Mar Apr May Jun July Aug Sept Oct Nov Dec Jan Feb Total
2018 - - - 100 - - - - - 6950 - 60 7110
2019 456.5 - 200.48 - 200 - - - - - 100 - 956.98
I can not use PIVOT
as it is not supported in my compact SQL Server version.
How can I do this?