前一行列值+当前行值

时间:2017-11-09 11:22:32

标签: sql sql-server-2008

我有这样的表:

id  valueA  valueB  ValueC 
--------------------------   
1   2       3       1         
2   3       2       0       
3   1       2       2      

我想得到:

id  valueA  valueB  ValueC  GSumABC
----------------------------------   
1   2       3       1       6  
2   3       2       0       11
3   1       2       2       16

最好的方法是什么?使用临时表,连接或其他东西?

3 个答案:

答案 0 :(得分:1)

在SQL Server 2008中,您可以使用cross apply

select t.*, tt.GSumABC
from t cross apply
     (select sum(valueA + valueB + ValueC) as GSumABC
      from t t2
      where t2.id <= t.id
     ) tt;

您也可以将此短语称为相关子查询:

select t.*,
       (select sum(valueA + valueB + ValueC) as GSumABC
        from t t2
        where t2.id <= t.id
       ) as GSumABC
from t;

答案 1 :(得分:1)

     select valueA,valueB,valueC,SUM(temp) over (order by t2.Id) as GTOTAL from
 temptable t1 
    left join (SELECT Id,(valueA + valueB + valueC ) as temp FROM temptable)
 as t2 on t1.Id = t2.Id ;

答案 2 :(得分:0)

with dat
as
(
  select 1 id,2 valueA,3 ValueB,1 ValueC union all
  select 2,3,2,0  union all      
  select 3,1,2,2 
)
select dat.id,
       dat.ValueA,dat.ValueB,dat.ValueC ,
       dat.ValueA+dat.ValueB+dat.ValueC total ,
       dat.ValueA+dat.ValueB+dat.ValueC+
        sum(case when dat_below.id<dat.id then 
                    dat_below.ValueA+dat_below.ValueB+dat_below.ValueC 
                 else 0 
            end ) rolling
from  dat cross join dat dat_below where dat_below.id <= dat.id
group by dat.id,
       dat.ValueA,dat.ValueB,dat.ValueC,dat.ValueA+dat.ValueB+dat.ValueC
order by 1