显示上一年的总和

时间:2016-04-07 20:54:51

标签: sql sql-server sql-server-2008 datetime sqldatetime

我有以下选择声明:

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

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

enter image description here

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

如果您使用的是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

答案 2 :(得分:0)

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

这是我得到的答案

fiscalYr |值| PrevYr |值

2014 | 165 | 2013 | NULL

2015 | 179 | 2014 | 165

2016 | 143 | 2015年| 179