各位大哥,又有了一个新问题。请出手相助啊~下面我列出了表t1和表t2的数据
t1表
id number class_id
06 2 596
74 4 597
74 1 598
74 6 599
74 13 600
77 10 601
90 8 602
t2表
id number class_id
06 2 596
74 4 597
74 1 598
74 2 599
74 3 599
90 3 602
90 5 602
要得到如下结果,该如何写sql?(t1表是一个库存表,t2表是已经使用表,现在要查询出:t1-t2 =剩余的。)
id number class_id
74 1 599
74 13 600
77 10 601
t1表
id number class_id
06 2 596
74 4 597
74 1 598
74 6 599
74 13 600
77 10 601
90 8 602
t2表
id number class_id
06 2 596
74 4 597
74 1 598
74 2 599
74 3 599
90 3 602
90 5 602
要得到如下结果,该如何写sql?(t1表是一个库存表,t2表是已经使用表,现在要查询出:t1-t2 =剩余的。)
id number class_id
74 1 599
74 13 600
77 10 601
解决方案 »
- 我做的web系统,为什么一有人做数据统计就提示无法连接数据库了啊,是sqlserver2005
- 有谁可以给个:通过锁来控制并发修改数据的例子 来学习一下吗?
- SQL 的连接问题?
- 急 急 急 ,一个莫名奇妙的问题,高手的问题
- 如何用SQL语句把重复的记录删除,只剩下一条记录,谢谢!
- 为何不能启动SQL SERVER服务管理器
- ms sql数据库的扩展名是哪个?*.mdf 或 *.ldf 或是别的?
- 关于建立数据库的问题,十万火急,高手帮帮忙
- Select幫忙
- 数据库连线问题?**<使用者sa登入失敗,原因末結合受信任SQL server连线>**???
- 我是菜鸟,求一个查询?
- 如何选择当前表中重复键名的最小ID数?
a.id,a.number-isnull(b.number,0) as number,a.class_id
from
t1 a
left join
(select id,sum(number) as number,class_id from t2 group by id,class_id) b
on
a.id=b.id and a.class_id=b.class_id
where
a.number-isnull(b.number,0)>0
insert into @t1 select '06',2 ,596
insert into @t1 select '74',4 ,597
insert into @t1 select '74',1 ,598
insert into @t1 select '74',6 ,599
insert into @t1 select '74',13,600
insert into @t1 select '77',10,601
insert into @t1 select '90',8 ,602
declare @t2 table(id varchar(6),number int,class_id int)
insert into @t2 select '06',2,596
insert into @t2 select '74',4,597
insert into @t2 select '74',1,598
insert into @t2 select '74',2,599
insert into @t2 select '74',3,599
insert into @t2 select '90',3,602
insert into @t2 select '90',5,602
select
a.id,a.number-isnull(b.number,0) as number,a.class_id
from
@t1 a
left join
(select id,sum(number) as number,class_id from @t2 group by id,class_id) b
on
a.id=b.id and a.class_id=b.class_id
where
a.number-isnull(b.number,0)>0/*
id number class_id
------ ----------- -----------
74 1 599
74 13 600
77 10 601
*/
id,sum(number) as number,class_id
from
(
select
id,number,class_id
from
t1
union all
select
id,-number,class_id
from
t2
) as t
group by
id,class_id
having
sum(number)>0