有两个表,结构如下
TB1(
PLNO 字符型,
FDNO 字符型,
SUM  数字代表金额
);TB2(
PLNO2 字符型,
FDNO2 字符型,
SUM2  数字代表金额
);现在要求,对TB1中的每条记录,如果TB2中有相同的POLNO和FDNO的值,
也就是有POLNO2=POLNO并且FDNO2=FDNO的记录的话(零到多条,如果有难度,可以考虑0到1条的情况),
求用TB1中的SUM值减去TB2中SUM2的值。注意,对TB1中的一条记录,TB2中并不一定总是有POLNO2=POLNO并且FDNO2=FDNO条件成立的语句存在。这样的SQL怎么写?是一条SQL就把TB1中的所有记录遍历一遍哦

解决方案 »

  1.   

    select a.sum1-b.sum2 as temp from tb1 a,tb2 b where a.plno=b.plno2 and a.fdno=b.fdno2没测试
      

  2.   

    忘了强调,如果TB2中没有对应的记录,TB1中的记录仍然需要在结果中(相当于SUM-0)。
    楼上的SQL,如果TB2中没有符合条件的记录,则结果中这些记录就没有了。
      

  3.   

    那就union一下好了
    select a.sum1-b.sum2 as temp from tb1 a,tb2 b where a.plno=b.plno2 and a.fdno=b.fdno2
    union
    select a.sum1 as temp from tb1 a, tb2 b where not (a.plno=b.plno2 and a.fdno=b.fdno2)
      

  4.   

    这样也试试看吧select a.sum1-(case when a.plno=b.plno2 and a.fdno=b.fdno2 then b.sum2 else 0 end) as temp from tb1 a,tb2 b
      

  5.   

    左连接
    select a.sum1-b.sum2 as temp from (tb1 a left join tb2 b on a.plno=b.plno2 and a.fdno=b.fdno2)
    这是在sql server中的写法,数据库不同写法会不一样
      

  6.   

    用left joinselect (a.sum1-b.sum2) as temp from (tb1 a left join tb2 b on a.plno=b.plno2 and a.fdno=b.fdno2)