2016-04-07 22 views
1

私は以下のようなselect文があります:前年から列previous_yearsum([value])後に追加する方法表示合計

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

を?

enter image description here

+1

['LAG/LEAD'](https://msdn.microsoft.com/en-us/library/hh231256.aspx)SQL Server 2012以降の場合は自己結合 – lad2025

+0

@ 4est喜んで助けてください! – DhruvJoshi

答えて

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

0

あなたが前の行の値を取得するためにLAGを使用することができます2012+ SQL Serverの使用している場合:

;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 
+0

それはSQL Server 2008です:/それを行う別の方法ですか? – 4est

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

関連する問題