这样的问题你能帮我吗?(两个结果集经过判断后合成一个集合) (153分)

  • 主题发起人 主题发起人 shadow_x
  • 开始时间 开始时间
S

shadow_x

Unregistered / Unconfirmed
GUEST, unregistred user!
有两个视图,它们都只有两个字段:resourceId和counter.
视图1的 resourceId 包含 视图2的 resourceId
我想这样:在新的集合中
视图1和视图2中有相同的 resourceId 的记录的counter是两者counter的和
视图2没有的resourceId 保持视图1的counter

我想写在数据库中,不知写成什么东西,也不知道如何写!!!
希望大侠拔刀相助!!!!

Delphi6 +WIN2000 +SQL sever2000

 
写在数据库中,可以写在存储过程中,也可以用视图
关于写法,关键的SQL语句如下,供参考(未测试):
select a.resourceId,
a.counter+b.counter
from 视图1 a join 视图2 b on
视图1.resourceId=2.resourceId(+)
 
select * into #temp from table1 where resourceid not in (select resourceid from
table2)
insert into #temp(resourceid,counter) select table1.counter+table2.counter
counter,table1.resourceid from table1 join table2 on table1.resourceid=
table2.resourceid
 
不好一时,刚才给的是ORACLE的语法,SQL2000用LEFTJOIN:
select a.resourceId,
a.counter+b.counter ------请自己注意NULL的发生问题
from 视图1 a Left Join 视图2 b on
视图1.resourceId=2.resourceId
 
to:V_Lucky
你的方法是不行的!
我说过:[red]视图1的 resourceId 包含 视图2的 resourceId [/red]
所以你的结果会造成视图2中没有的resourceId 的记录的counter会变成 NULL
因为: 任何值+NULL=NULL
to:hj5000
你的我还没看懂,等一下我试试看!
 
to:V_Lucky

》?-----请自己注意NULL的发生问题
NULL的问题如何解决呢?
谢谢您的关注
 
把V_Lucky的稍改一下:
select a.resourceId,
a.counter+isnull(b.counter,0)
from 视图1 a Left Join 视图2 b on
a.resourceId=b.resourceId
 
要用left join,不可以用=连接,那样会少记录的
 
about null,
in oralce we can use function nvl(),
i dont know what in sqlserver.
 
select resourceid,counter+isnull(select counter from view2
where resourceid=view1.resourceid,0)
from view1
试验一下这个如何?
 
用左连接,不过,速度可能有问题(如果你有几万条记录的话)
select a.resourceId,
a.counter+isnull(b.counter,0)
from 视图1 a left join 视图2 b on
a.resourceId=b.resourceId
 
多人接受答案了。
 
后退
顶部