Please try the below query for SQL 2008
select t1.[Fiscal Year],t1.Value,(t1.[Fiscal Year]-1) [previous_year],t2.Value [previous_value]
from
( select [Fiscal Year], sum([value]) value
from [table1]
group by [Fiscal Year]
)t1
LEFT JOIN
(
select [Fiscal Year], sum([value]) value
from [table1]
group by [Fiscal Year]
)t2
ON t1.[Fiscal Year]=t2.[Fiscal Year]+1
If you are using SQL Server 2012+ you can use LAG
to get the value of the previous row:
;with cte as (
select [Fiscal Year], sum([value]) AS value,
from [table1]
group by [Fiscal Year]
)
select [Fiscal Year], value,
[Fiscal Year] - 1, lag(value) over (order by [Fiscal Year]) as prev_value
from cte
--to prepare the environment, let said this is your table
declare @table table
(
fiscalYr integer,
Value integer,
previousyr integer,
prevValue integer
)
--to prepare the value, let said these are your value
insert into @table values (2014,165,2013,0);
insert into @table values (2015,179,2014,0);
insert into @table values (2016,143,2015,0);
--the SQL
select A.fiscalYr,A.Value,A.previousyr, B.Value
from @table A left join
@table B on B.fiscalYr = A.previousyr
This the answer I got
fiscalYr| value| PrevYr| Value
2014| 165| 2013| NULL
2015| 179| 2014| 165
2016| 143| 2015| 179
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.