导航
  • 主页
  • 基础类
  • 应用实例
  • 新技术前沿

表A的字段减去表B的字段之和,如何写SQL语句?

麻酱面条 老师  2007-12-06 10:34:40
情况大致如下:
表A:
id1 id2 id3 dj sl
a1 a2 a3 3 100
b1 b2 b3 5 50
......
表A是存货表,id1、id2、id3是货物信息,dj表示单价,sl表示数量。

表B:
id1 id2 id3 dj sl
a1 a2 a3 3 45
a1 a2 a3 3 15
b1 b2 b3 5 20
.......
表B是出货表,sl表示从表A中取出的货物数量。

现在想做一个查询,显示的记录如下:
id1 id2 id3 dj sl
a1 a2 a3 3 40
b1 b2 b3 5 30
也就是这里显示的sl是表A的sl减去表B数量之和,40=100-45-15 , 30=50-20,
SQL语句该如何写,多谢大家!!!
...全文
59 点赞 收藏 6
写回复
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
-狙击手- 2007-12-06
B表是多条呀

select a.id1,a.id2,a.id3,a.dj ,sum(a.sl - b.sl)
from tablea a
left join (select id1,id2,ide3 ,sum(sl)as sl from tableb group by id1,ide2,id3) b
on a.id1 = b.id1 and a.id2 = b.id2 and a.id3 = b.id3
group by a.id1,a.id2,a.id3
回复
duanzhi1984 2007-12-06
try
--
select a.id1,a.id2,a.id3,a.dj,a.sl-b.sl as sl
from A a join (select id1,id2,id3,dj,sum(sl) sl from B group by id1,id2,id3,dj) b
on a.id=b.id and a.id2=b.id2 and a.id3=b.id3

回复
-狙击手- 2007-12-06
select a.id1,a.id2,a.id3,a.dj ,sum(a.sl - b.sl)
from tablea a
left join tableb b
on a.id1 = b.id1 and a.id2 = b.id2 and a.id3 = b.id3
group by a.id1,a.id2,a.id3
回复
中国风 2007-12-06
select 
a.id1,a.id2,a.id3,a.dj,
[sl]=a.sl-t.s1
from
a
join
(select id1,id2,id3,sum(sl)as s1 from b group by id1,id2,id3)T
on t.id1=a.id1 and t.id2=a.id2 and t.id3=a.id3
回复
中国风 2007-12-06
select 
a.id1,a.id2,a.id3,a.dj,
[sl]=a.sl-(select sum(sl) from b where id1=a.id1 and id2=a.id2 and id3=a.id3)
from
a
回复
中国风 2007-12-06
select 
a.id1,a.id2,a.id3,a.dj,
[sl]=a.sl-(select sum() from b where id1=a.id1 and id2=a.id2 and id3=a.id3)
from
a
回复
发动态
发帖子
MS-SQL Server
创建于2007-09-28

3.2w+

社区成员

MS-SQL Server相关内容讨论专区
申请成为版主
社区公告
暂无公告