日期:2014-05-18 浏览次数:20436 次
[code=SQL]create table A(id int, code int, stock int, kc int) insert into A values(1, 11 , 3 , 4 ) insert into A values(2, 22 , 4 , 19) insert into A values(3, 33 , 4 , 5 ) insert into A values(4, 44 , 7 , 2 ) insert into A values(5, 55 , 9 , 7 ) create table B(id int, num int,state int) insert into B values(4, 3 ,0 ) insert into B values(2, 6 ,1) insert into B values(1, 1 ,1) insert into B values(2, 9 ,1) insert into B values(5, 2 ,1) insert into B values(5, 5 ,0) select a.id,a.code,a.stock,a.kc,bb.num from a left join (select id,sum(case when state =0 then 0 else num end) as num from b group by id) bb on a.id = bb.id where a.kc <> a.stock + isnull(bb.num,0) drop table a,b /* id code stock kc num ----------- ----------- ----------- ----------- ----------- 3 33 4 5 NULL 4 44 7 2 0 5 55 9 7 2 (所影响的行数为 3 行) */