显示上一年的总和

Display sum from previous year

我有如下 select 语句:

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

如何在上一年的 previous_yearsum([value]) 列之后添加?

如果您使用的是 SQL Server 2012+,您可以使用 LAG 获取上一行的值:

;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

请尝试以下查询 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

--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

这就是我得到的答案

财政年度|价值|上一页|值

2014| 165| 2013|空

2015| 179| 2014| 165

2016| 143| 2015| 179