日期:2014-05-17 浏览次数:20587 次
create table 表A
(ID int, 单号 varchar(10))
insert into 表A
select 1, 'YD001' union all
select 2, 'YD002' union all
select 3, 'YD003'
create table 表B
(ID int, AID int, 订单号 varchar(10), 数量 int)
insert into 表B
select 1, 1, '0001', 11 union all
select 2, 1, '0002', 11 union all
select 3, 2, '0001', 22 union all
select 4, 2, '0003', 33 union all
select 5, 3, '0001', 11 union all
select 6, 3, '0002', 55
select b.订单号,
(select sum(数量)
from 表B c
where c.订单号=b.订单号
and c.ID<=b.ID) '数量'
from 表A a
inner join 表B b on a.ID=b.AID
where a.单号='YD002'
/*
订单号 数量
---------- -----------
0001 33
0003 33
(2 row(s) affected)
*/
--楼上的实现不了
if object_id('A') IS NOT NULL
DROP TABLE A
go
create table A
(
id int primary key identity(1,1),
[单号] varchar(10)
)
go
if object_id('B') IS NOT NULL
DROP TABLE B
go
create table B
(
id int primary key identity(1,1),
aid int,
[订单号] varchar(10),
[数量] int
)
go
insert into a
select 'YD001' UNION ALL
select 'YD002' U