当前位置: 代码迷 >> Sql Server >> 还是问sql语句,该怎么解决
  详细解决方案

还是问sql语句,该怎么解决

热度:158   发布时间:2016-04-27 19:19:43.0
还是问sql语句
表1 
id code stock kc
1 11 3 4
2 22 4 19
3 33 5 5
4 44 7 2
5 55 9 7
表二 
id num 
4 3 
2 6
1 1
2 9
5 2
5 5
如何得到所有的 stock+num<>kc的记录,就像

id code stock num kc
4 44 7 0 2
5 55 9 7 7


------解决方案--------------------
Java code
[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.numfrom aleft join (select id,sum(case when state =0 then 0 else num end) as num from b group by id) bbon 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           NULL4           44          7           2           05           55          9           7           2(所影响的行数为 3 行)*/
  相关解决方案