如何查找两个表之间的相差数的记录

xej 2006-05-15 09:17:36
本人在SQL的后台写了一个单据的存储过程,有一步不知如何实现。例如有两个获至宝临时表
select * from #t1
id tity
139 12.2
142 22
select * from #t2
id tity barcode
139 22.2 I200604100000001
140 22.2 123456
142 22 55
请教各位,如何根据表中的#t2.tity减去#t1.tity得出记录
id tity barcode
139 10 I200604100000001
142 22 55
...全文
206 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
free_pop 2006-05-16
  • 打赏
  • 举报
回复
Create Table #t1
(id Int,
tity Numeric(10,1))
Create Table #t2
(id Int,
tity Numeric(10,1),
barcode Varchar(20))
Insert #t1 Select 139, 12.2
Union All Select 142, 22
Insert #t2 Select 139, 22.2,'I200604100000001'
Union All Select 140, 22.2,'12345'
Union All Select 142, 22,'55'
GO
select * from #t1
select * from #t2
select a.id,a.tity-b.tity,a.barcode from #t2 as a,#t1 as b where (a.id=b.id and a.tity<>b.tity)
union select * from #t2 where id not in(select id from #t1)
love_free 2006-05-16
  • 打赏
  • 举报
回复

select a.id,isnull(a.tity,0)-isnull(b.tity,0) as tity,a.barcode from #t2 as a left join #t1 as b on a.id=b.id
where isnull(a.tity,0)-isnull(b.tity,0)<>0
love_free 2006-05-16
  • 打赏
  • 举报
回复
select top 1 a.id,a.tity-isnull(b.tity,0) as tity,a.barcode from #t2 as a, #t1 as b where (a.id<>b.id and a.tity-b.tity>0)
paoluo 2006-05-16
  • 打赏
  • 举报
回复
Create Table #t1
(id Int,
tity Numeric(10,1))
Create Table #t2
(id Int,
tity Numeric(10,1),
barcode Varchar(20))
Insert #t1 Select 139, 12.2
Union All Select 142, 22
Insert #t2 Select 139, 22.2,'I200604100000001'
Union All Select 140, 22.2,'12345'
Union All Select 142, 22,'55'
GO
Select * From
(Select
A.id,
A.tity-IsNull(B.tity,0) As tity,
A.barcode
From #t2 A Left Join #t1 B
On A.id=B.id) A
Where tity<>0
GO
Drop Table #T1,#t2
--Result
/*
139 10.0 I200604100000001
140 22.2 12345
*/
xej 2006-05-15
  • 打赏
  • 举报
回复
sorry 上面的哪些写的不太仔细,有小小失误.我的原意是,
有两个临时表
select * from #t1
id tity
139 12.2
142 22
select * from #t2
id tity barcode
139 22.2 I200604100000001
140 22.2 123456
142 22 55
而我想要的结果
id tity barcode
139 10 I200604100000001
140 22.2 123456
#t2的139这条记录#t2.tity-#t1.tity的还有10,所以要显示,#t2的140这条记录#t1没,所以要显示,#t2的142这条记录#t2.tity-#t1.tity刚好减完,所以不用显示
xej 2006-05-15
  • 打赏
  • 举报
回复
lxzm1001(*蓝星之梦*) 的回答还是没有实现所要的结果,它的结果是
id tity barcode
139 10 I200604100000001
142 0 55
而我相要的是这个语句的结果
id tity barcode
139 10 I200604100000001
140 22.2 55
的第一行的数据(上面定的时候有小小失误,sorry),我写的语句是这样
select top 1 a.id,a.tity,a.barcode from #t2 as a, #t1 as b where (a.id<>b.id and a.tity-b.tity>0)。但是实现不了,哪位帮我改改这条语句。
lxzm1001 2006-05-15
  • 打赏
  • 举报
回复
select a.id,b.tity-a.tity,b.barcode from #t1 a,#t2 b where a.id=b.id
lxzm1001 2006-05-15
  • 打赏
  • 举报
回复
select a.id,b.tity-a.tity,b.barcode from #t1 a,#t1 b where a.id=b.id

27,580

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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