日期:2014-05-17  浏览次数:20711 次

子查询与表连接关系,能否彼此替换


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


不是说子查询和表连接可以替换吗,上面这段SQL ,能用表连接写出吗
SQL

------解决方案--------------------
select b.订单号,SUM(a.数量) from 表B a,表B b 
where a.订单号=b.订单号 and a.ID<=b.ID
group by b.订单号,b.id

这样?感觉你的表A没用上似的