我需要创建具有累积总和的表: - 如果行中没有任何值,则值和 null 的总和给出 null
我想从中创建累积总和的初始表如下所示:
+--------------------+---------------+------+-----+---------+-------+
| First_mob | r2009 | r2010|r2011| r2012 | r2013 |
+--------------------+---------------+------+-----+---------+-------+
| 0 | 1 | NULL |NULL | NULL |NULL |
| 1 | 3 | 1 | 2 | 3 |3 |
| 2 | 6 | 6 | 3 | NULL |NULL |
| 3 | 10 | 17 | NULL| NULL |5 |
| 4 | 61 | 23 | NULL| 4 |NULL |
+--------------------+---------------+------+-----+---------+-------+
我想要获得的表看起来像
+--------------------+---------------+------+-----+---------+-------+
| First_mob | r2009 | r2010|r2011| r2012 | r2013 |
+--------------------+---------------+------+-----+---------+-------+
| 0 | 1 | NULL |NULL | NULL |NULL |
| 1 | 4 | 1 | 2 | 3 |3 |
| 2 | 10 | 7 | 5 | 3 |3 |
| 3 | 20 | 24 | NULL| 3 |8 |
| 4 | 81 | 47 | NULL| 7 |NULL |
+--------------------+---------------+------+-----+---------+-------+
我的累积总和的 sql 代码如下所示:
if OBJECT_ID('tempdb..#suma_risk_prestige_nbr') IS NOT NULL drop table #suma_risk_prestige_nbr
select tp1.first_mob_InDef,
SUM(tp2.r2007) as r2007,
SUM(tp2.r2008) as r2008,
SUM(tp2.r2009) as r2009,
SUM(tp2.r2010) as r2010,
SUM(tp2.r2011) as r2011,
SUM(tp2.r2012) as r2012,
SUM(tp2.r2013) as r2013
into #suma_risk_prestige_nbr
from #risk_prestige_nbr tp1
inner join #risk_prestige_nbr tp2 on tp1.first_mob_InDef>=tp2.first_mob_InDef
group by tp1.first_mob_InDef,tp1.r2007,tp1.r2008,tp1.r2009,tp1.r2010,
tp1.r2011,tp1.r2012,tp1.r2013
order by tp1.first_mob_InDef,tp1.r2007,tp1.r2008,tp1.r2009,tp1.r2010,
tp1.r2011,tp1.r2012,tp1.r2013
谢谢