sql - How to calculate sum of the years into a new column for Current to previouse years -
i using sql server 2012, how can achieve following(table 2) output table 1 sql script/tsql?
table 1 :current scenario
-------------------------------------------------- year referredeachyear activeeachyear -------------------------------------------------- 2014 297 179 2013 321 144 2012 354 123 2011 317 90 2010 292 72 --------------------------------------------------
table 2 : expected output
------------------------------------------------------------------------- year referredeachyear activeeachyear totalactiveinsystem ------------------------------------------------------------------------- 2014 297 179 608 2013 321 144 429 2012 354 123 285 2011 317 90 162 2010 292 72 72 --------------------------------------------------------------------------
if using sql server 2012, can use cumulative sum function:
select cs.*, sum(cs.activeeachyear) on (order cs.[year]) totalactiveinsystem currentscenario cs order cs.[year] desc;
this function not available in earlier versions of sql server. have use other method in versions (i use correlated subquery).
Comments
Post a Comment