首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

这一列怎么计算

2013-01-26 
这一列如何计算开始数据m1m2m310010NULL10010NULL10010NULL最终数据m1m2m310010100-10901001090+100-101

这一列如何计算
开始数据
m1m2m3
10010NULL
10010NULL
10010NULL
最终数据
m1m2m3
10010100-10=90
1001090+100-10=180
10010180+100-10=270
说明:
m3的值,第一行为m1-m2,其他行的均为上一行的m3+本行的m1-本行的m2

测试数据


if OBJECT_ID('t') is not null
drop table t
go
create table t
(
m1 int,
m2 int,
m3 int
)
go
insert into t values(100,10,null),
(100,10,null),
(100,10,null)
table
[解决办法]
declare @m3 int
set @m3 = 0
update t
set @m3 = @m3 + m1 - m2
   ,m3 - @m3


[解决办法]

----------------------------
-- Author  :TravyLee(物是人非事事休,欲语泪先流!)
-- Date    :2013-01-11 10:32:21
-- Version:
--      Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86) 
--Jul  9 2008 14:43:34 
--Copyright (c) 1988-2008 Microsoft Corporation
--Developer Edition on Windows NT 6.1 <X86> (Build 7601: Service Pack 1)
--
----------------------------
--> 测试数据:[test]
if object_id('[test]') is not null drop table [test]
go 
create table [test]([m1] int,[m2] int,[m3] int)
insert [test]
select 100,10,null union all
select 100,10,null union all
select 100,10,null

select * from [test]
go


alter table test add id  int identity
go


update test
set [m3]=(select SUM([m1]-[m2]) from test b where test.id>=b.id)

alter table test drop column id
select * from test
/*
m1m2m3
-----------------------------
1001090
10010180
10010270
*/

热点排行