Sql server 2008 希望按原始和;SQL Server中的列
下面是我的实际数据Sql server 2008 希望按原始和;SQL Server中的列,sql-server-2008,Sql Server 2008,下面是我的实际数据 select Year,fall_unit,summer_unit,spring_unit from ( select 2010 as Year,4 fall_unit,5 summer_unit,6 spring_unit union select 2011 as Year,7 fall_unit,23 summer_unit,90 spring_unit union select 2012 as Year,3 fall_unit,2 summer_unit,5 sprin
select Year,fall_unit,summer_unit,spring_unit
from (
select 2010 as Year,4 fall_unit,5 summer_unit,6 spring_unit
union
select 2011 as Year,7 fall_unit,23 summer_unit,90 spring_unit
union
select 2012 as Year,3 fall_unit,2 summer_unit,5 spring_unit) M
还想按原始值和列进行累积求和
所需输出如下所示
2010 4 9 15
2011 22 45 135
2012 138 140 145
下面是计算的更多说明
2010 : 9 = (4+5)
2010 : 15 = (9+6)
2011 : 22 = (15+7)
2011 : 45 = (22+23)
2011 : 135= (45+90)
2012 : 138= (135+3)
2012 : 140= (138+2)
2012 : 145= (140+5)
尝试更新的查询(最后一个查询)。我理解的输出逻辑是:年份| C1:秋季+上一年度|总计| C2:秋季+夏季+上一年度计数| C3:总计
create table #test(Year int, fall_unit int, summer_unit int, spring_unit int)
insert #test (Year, fall_unit, summer_unit, spring_unit)
select 2010 as Year,4 fall_unit,5 summer_unit,6 spring_unit
union
select 2011 as Year,7 fall_unit,23 summer_unit,90 spring_unit
union
select 2012 as Year,3 fall_unit,2 summer_unit,5 spring_unit
-- select * from #test
select t2.Year,
case when t1.fall_unit IS NULL then t2.fall_unit
else SUM(t1.rowTotal) OVER (ORDER BY t1.YEAR) + t2.fall_unit
end as C1,
case when t1.summer_unit IS NULL then t2.summer_unit + coalesce(t1.rowTotal, 0) + t2.fall_unit
else SUM(t1.rowTotal) OVER (ORDER BY t1.YEAR) + t2.fall_unit + t2.summer_unit
end as C2,
SUM(t2.rowTotal) OVER (ORDER BY t1.YEAR) as C3
from (select t.*, t.fall_unit + t.summer_unit + t.spring_unit as rowTotal from #test t) t1
right join (select t.*, t.fall_unit + t.summer_unit + t.spring_unit as rowTotal from #test t) t2
on t1.YEAR+1 = t2.YEAR
order by t2.Year
它只提供了总计,我想要的是所需输出中描述的累计总计。@Sandip,我更新了答案(查询)以检索所需输出。