我有一个简单的表,其中只包含几千条记录,其中性能不是主要考虑因素。
我想计算列表中1
和5
年间隔的同一列中值之间的差异。
例如,我们说我有一张这样的表:
Name, Year, Value<br>
Joe 2014 25<br>
Joe 2013 22<br>
Joe 2012 26<br>
Joe 2011 18<br>
Joe 2010 21<br>
Mark 2014 33<br>
Mark 2013 31<br>
Mark 2012 34<br>
Mark 2011 28<br>
Mark 2010 18<br>
它可以追溯到几年前。
我想为1 year change
和5 year change
添加两列关于给定名称的运行差异。
所以完成的输出看起来像这样(如果可能的话):
Name, Year, Value, 1-yr-change, 5-yr-change<br>
Joe 2014 25 3 4<br>
Joe 2013 22 -4 <whatever 2013-2009 is><br>
Joe 2012 26 8 <br>
Joe 2011 18 -3<br>
Joe 2010 21 <whatever 2010-2009 is><br>
Mark 2014 33 2 15<br>
Mark 2013 31 -3 <whatever 2013-2009 is><br>
Mark 2012 34 6<br>
Mark 2011 28 10<br>
Mark 2010 18 <whatever 2010-2009 is><br>
这是我尝试使用表格中的实际列的原因:
select t1.Agency, t1.FY, t1.[Tax Appropriations],<br>
case when t2.FY = T1.FY - 1 then T1.[Tax Appropriations] - T2.[Tax Appropriations] else null end as '1-yr-change',<br>
case when t2.FY = T1.FY - 5 then T1.[Tax Appropriations] - T2.[Tax Appropriations] else null end as '5-yr-change'<br>
from dbo.SHEFMain as t1<br>
left JOIN dbo.SHEFMain as t2 on T1.Agency = T2.Agency and T2.FY < T1.FY<br>
order by agency, fy desc<br>
结果有效,但是还有很多额外的重复行也带有空值 - 所以我显然误解了连接过程或类似的东西。
答案 0 :(得分:0)
我在另一个论坛上得到了答案 - 感谢您的帮助!这就是我得到的东西,似乎完美无缺。如果您有任何意见或疑虑,请与我们联系:
select t1.Agency
, t1.FY
, t1.[Tax Appropriations]
, t1.[Tax Appropriations] - (SELECT T2.[Tax Appropriations]
FROM dbo.SHEFMain as t2
WHERE T2.Agency = T1.Agency
AND T2.FY = T1.FY-1) as '1-yr-change'
, t1.[Tax Appropriations] - (SELECT T3.[Tax Appropriations]
FROM dbo.SHEFMain as t3
WHERE t3.Agency = T1.Agency
AND T3.FY = T1.FY-5) as '5-yr-change'
from dbo.SHEFMain as t1
order by T1.agency,
T1.fy DESC