T-SQL上一年总计明年列

时间:2014-10-01 10:34:32

标签: sql sql-server-2008-r2 sql-server-2012

我目前有一个看起来像这样的表:

fscYear ID          Days    #Invoices     AVG
2011    20000807    221     7             27
2012    20000807    403     15            25
2013    20000807    390     14            26
2014    20000807    119     4             23

我想在明年加入前一年的AVG,如下:

fscYear ID          Days    #Invoices   AVG  prevAVG
2011    20000807    221     7           27    0
2012    20000807    403     15          25    27
2013    20000807    390     14          26    25
2014    20000807    119     4           23    26

我如何实现这一目标?

编辑 SQL非常简单,

select * from theTableThatHoldsThedata

2 个答案:

答案 0 :(得分:2)

大多数数据库都支持ANSI标准窗口函数。您可以使用lag()

执行此操作
select t.*, coalesce(lag(avg) over (order by by fscyear), 0) as prevAVG
from atable t;

这适用于SQL Server 2012+。对于早期版本,您可以使用相关子查询或apply

select t.*, coalesce(tprev.prevAvg, 0) as prevAvg
from atable t outer apply
     (select top 1 t2.Avg as prevAvg
      from atable t2
      where t2.fscyear < t.fscyear
      order by t2.fscyear desc
     ) tprev;

答案 1 :(得分:0)

你可以写成:

SELECT Cur.fscYear ,Cur.ID,Cur.Days,Cur.#Invoices,Cur.AVG,  
       isnull(Prv.AVG,0) AS prevAVG
FROM test  AS Cur
LEFT OUTER JOIN test AS Prv
ON Cur.fscYear = Prv.fscYear + 1;

Demo