一道SQL语句问题

来源:百度知道 编辑:UC知道 时间:2024/09/23 12:04:55
表1 A
ID value date
* * *
表2 B
ID value date
* * *
条件:A.ID=B.ID and A.date=B.date
目的:显示A中的每条结果,但其中的value=A.value-B.value
提示:A中可能有很多条记录,而B中可能只有几条记录
问题:用SQL语句执行
例子:
A
201 10.00 2009-5
202 5 2009-6
201 20 2009-4
B
201 5 2009-4

结果:
201 10.00 2009-5
202 5 2009-6
201 15 2009-4
我只能试试,谢谢大家,好用的我会采纳的

楼上基本正确,但是有些小地方不注意,我这里稍微修改一下
select
t1.ID,t1.Date,t1.Value-isnull(t2.Value,0) as Value/*忘记null处理了,要是不处理的话,会出n多得空值*/
from
(select ID,Date,sum(value) as value from A group by ID,date)t1
left join
(select ID,Date,sum(value) as value from B group by ID,date)t2 on t1.ID=t2.ID and t1.Date=t2.Date

其实我觉得这个程序根本用不到子查询,用下面的语句可能会更有效率
select
t1.ID,t1.Date,t1.Value-isnull(t2.Value,0) as Value
from A t1
left join B t2 on t1.ID=t2.ID and t1.Date=t2.Date

如果可以用临时表就容易解决了

select A.ID,A.value-B.value,A.date from A,B
where A.ID=B.ID and A.date=b.date

select
t1.ID,t1.Date,t1.Value-t2.Value as Value
from
(select ID,Date,sum(value) as value from A group by ID,date)t1
left join
(select ID,Date,sum(value) as value from B group by ID,date)t2 on t1.ID=t2.ID and t1.Date=t2.Date