插入查询结果的问题:

abcd4321 2003-10-11 10:47:24
表A:
id count
1 100
2 200
3 300
4 400
表B:
id out
2 20
4 600
表C:(不是新建表)
id plus negative
2 180 null
4 null 200

查询A.id=B.id的结果,并判断查询结果的A.ount-B.out的数值的正负,若结果为正数则结果写入plus字段,若结果为负数则结果写入negative字段。
如果在表C中还有其他的字段,而生成新的记录的时候暂时不用写入数据,我该怎么做?
...全文
43 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
wzh1215 2003-10-11
  • 打赏
  • 举报
回复

create table C([id] int,plus int,negative int,other varchar(100))
create table A([id] int,[count] int)
insert into A([id],[count])
values(1,100)
insert into A([id],[count])
values(2,200)
insert into A([id],[count])
values(3,300)
insert into A([id],[count])
values(4,400)
create table B([id] int, out int)
insert into B([id],out)
values(2,20)
insert into B([id],out)
values(4,600)
insert into C([id],plus,negative)
select A.id,(case when (A.[count]-B.out)>0 then (A.[count]-B.out) end),(case when (A.[count]-B.out)<0 then (B.out-A.[count]) end)
from A,B where A.id=B.id
select * from C
结果为:

id plus negative other
----------- ----------- ----------- --------------------
2 180 0 NULL
4 0 200 NULL

(2 row(s) affected)


yujohny 2003-10-11
  • 打赏
  • 举报
回复
insert into tableC(id,plus,negative)
select A.id,case when a.count-b.out>=0 then a.count-b.out end,
case when a.count-b.out>=0 then a.count-b.out end
from A,B where A.id=B.id
txlicenhe 2003-10-11
  • 打赏
  • 举报
回复
insert c (id,plus,negative)
select a.id,(case when a.[count]-b.[out]>=0 then a.[count]-b.[out] end),(case when a.[count]-b.[out]<0 then b.[out]-a.[count] end)
from a join b on a.id = b.id
friendliu 2003-10-11
  • 打赏
  • 举报
回复
insert into tableC(id,plus,negative)
select a.id,case when a.count-b.out>=0 then a.count-b.out end,
case a.count-b.count<0 then b.out-a.count end
from a,b where a.id=b.id
pengdali 2003-10-11
  • 打赏
  • 举报
回复
insert c (id,plus,negative) select a.id,case when a.[count]-b.[out]>=0 then a.[count]-b.[out] end,case when a.[count]-b.[out]<0 then b.[out]-a.[count] end from a,b where a.id=b.id

34,874

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧