--示例--示例数据
create table 表一(Item varchar(10),Qty int)
insert 表一 select 'A',10
union all select 'A',12
union all select 'A',14
union all select 'B',13
union all select 'B',60
union all select 'C',30
union all select 'C',40
union all select 'C',10 create table 表二(Item varchar(10),Qty int)
insert 表二 select 'A',1000
union all select 'B',70
union all select 'C',100
go--查询
select id=identity(int),* into # from 表一
select a.Item,a.Qty,Result=b.Qty-(select sum(Qty) from # where Item=a.Item and id<=a.id)
from # a,表二 b
where a.Item=b.Item
drop table #
go--删除测试
drop table 表一,表二/*--结果
Item Qty Result
---------- ----------- -----------
A 10 990
A 12 978
A 14 964
B 13 57
B 60 -3
C 30 70
C 40 30
C 10 20(所影响的行数为 8 行)
--*/
create table 表一(Item varchar(10),Qty int)
insert 表一 select 'A',10
union all select 'A',12
union all select 'A',14
union all select 'B',13
union all select 'B',60
union all select 'C',30
union all select 'C',40
union all select 'C',10 create table 表二(Item varchar(10),Qty int)
insert 表二 select 'A',1000
union all select 'B',70
union all select 'C',100
go--查询
select id=identity(int),* into # from 表一
select a.Item,a.Qty,Result=b.Qty-(select sum(Qty) from # where Item=a.Item and id<=a.id)
from # a,表二 b
where a.Item=b.Item
drop table #
go--删除测试
drop table 表一,表二/*--结果
Item Qty Result
---------- ----------- -----------
A 10 990
A 12 978
A 14 964
B 13 57
B 60 -3
C 30 70
C 40 30
C 10 20(所影响的行数为 8 行)
--*/
解决方案 »
- 数据datetime条件查询如何忽略前面的日期
- 求助Sql2008用户权限问题(涉及到跨数据库)
- SQL语句无法查询到中文字段
- 进来看下,非常感谢,不需要动脑子.....
- 急!!!请求一个简单的方法,最好是直接的sql语句能得到所需结果,详见内。
- 存储过程中的逻辑问题,进者有分
- 存储过程中使用动态sql语句,执行时输入参数提示列名无效
- 在"delphi 5 中怎样将一条记录加入到"StringGrid"中,在线等。。.
- 请问COMMIT TRANSACTION命令是什么时候工作?
- 关于cbuilder中属性的问题!散分!来者有分,你们辛苦了!
- sqlserver中有没有这种功能?
- 计算时间问题,近来看看.
create table 表一(Item varchar(10),Qty int)
insert 表一 select 'A',10
union all select 'A',12
union all select 'A',14
union all select 'B',13
union all select 'B',60
union all select 'C',30
union all select 'C',40
union all select 'C',10 create table 表二(Item varchar(10),Qty int)
insert 表二 select 'A',1000
union all select 'B',70
union all select 'C',100
go--查询
select id=identity(int),a.*,Result=b.Qty
into # from 表一 a,表二 b
where a.Item=b.Item
order by a.Item
declare @Item varchar(10),@s int
update # set
@s=case when @Item=Item then @s-Qty else Result-Qty end,
@Item=Item,Result=@s
select * from #
drop table #
go--删除测试
drop table 表一,表二/*--结果
Item Qty Result
---------- ----------- -----------
A 10 990
A 12 978
A 14 964
B 13 57
B 60 -3
C 30 70
C 40 30
C 10 20(所影响的行数为 8 行)
--*/