我有两个表,第一个表a中的内容为
spid pihao shl xsshl sxrq
1000 080808 10 0 2008-08-08
第二个表b的结构如下(此表为临时表,每次操作前没有任何数据)
spid shl
我经常使用下面的语句查询第一个表的数据
select distinct a.pihao,a.shl-isnull(xsshl,0) as hwshl,a.sxrq from sphwph a(nolock)
where and a.shl-isnull(a.xsshl,0)<>0
order by sxrq
我现在要与在上面的语句中用到第二张表的内容位置如下
select distinct a.pihao,a.shl-isnull(xsshl,0)-b.shl as hwshl,a.sxrq
from a(nolock),b(nolock)
where and a.shl-isnull(a.xsshl,0)<>0 and a.spid=b.spid
order by sxrq
但问题是如果表b中没有数据的时候无法查到数据,现在想实现如果表b没有数据或没有与a相同的数据,
那么上面的b.shl将为0,如果b中有和a中相同的数据那么将减去b中的b.shl
但是不能用if语句
spid pihao shl xsshl sxrq
1000 080808 10 0 2008-08-08
第二个表b的结构如下(此表为临时表,每次操作前没有任何数据)
spid shl
我经常使用下面的语句查询第一个表的数据
select distinct a.pihao,a.shl-isnull(xsshl,0) as hwshl,a.sxrq from sphwph a(nolock)
where and a.shl-isnull(a.xsshl,0)<>0
order by sxrq
我现在要与在上面的语句中用到第二张表的内容位置如下
select distinct a.pihao,a.shl-isnull(xsshl,0)-b.shl as hwshl,a.sxrq
from a(nolock),b(nolock)
where and a.shl-isnull(a.xsshl,0)<>0 and a.spid=b.spid
order by sxrq
但问题是如果表b中没有数据的时候无法查到数据,现在想实现如果表b没有数据或没有与a相同的数据,
那么上面的b.shl将为0,如果b中有和a中相同的数据那么将减去b中的b.shl
但是不能用if语句
from a(nolock) left join b(nolock)
on a.shl-isnull(a.xsshl,0) <>0 and a.spid=b.spid
order by sxrq
go
insert ta select 1000 ,'080808', 10 , 0 , '2008-08-08'
go
create table tb(spid int, shl int)
go
select distinct a.pihao,a.shl-isnull(xsshl,0)-isnull(b.shl,0) as hwshl,a.sxrq
from ta a left join tb b
on a.shl-isnull(a.xsshl,0) <>0 and a.spid=b.spid
order by sxrq drop table ta,tb/*pihao hwshl sxrq
--------- ----------- ------------------------------------------------------
080808 10 2008-08-08 00:00:00.000(所影响的行数为 1 行)
*/