简体   繁体   中英

Display sum from previous year

I have select statement like below:

  select [Fiscal Year], sum([value]), 
         YEAR(DATEADD(year,-1,[Fiscal Year])) as previous_year
  from [table1] 
  group by [Fiscal Year]

How to add after column previous_year , sum([value]) from previous year?

在此处输入图片说明

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

SQL demo link

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.

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