有表A:
ID 单号 .......
1 YD001
2 YD002
3 YD003
表B:
ID AID 订单号 数量
1 1 0001 11
2 1 0002 11
3 2 0001 22
4 2 0003 33
5 3 0001 11
6 3 0002 55
这里的ID都是自动增长的,我现在想要实现 比如在A.单号=YD0002时的这个单号中所包含的订单号,在这个订单(包含)之前的数量和。
以YD002为例:
其它包含 0001 、 0003订单号 想要输出以下结果
0001 33
0003 33
这个要怎么实现 谢谢!
------解决方案--------------------
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' UNION ALL
select 'YD003'