日期:2014-05-18  浏览次数:20570 次

问一sql语句两表某列数据相减
比如表1
ID count
1 2
2 3
4 1
5 4

表2
ID count
2 2
3 3
5 6
7 1
我要的结果是表1减去表2的结果
结果如下
ID count
1 2
2 1
3 -3
4 1
5 -2
7 -1

------解决方案--------------------
探讨
select isnull(m.id,n.id) id ,
isnull(m.count , 0) - isnull(n.count , 0) [count]
from t1 full join t2
on t1.id = t2.id
order by id

------解决方案--------------------
SQL code

--> 测试数据:[表1]
if object_id('[表1]') is not null drop table [表1]
create table [表1]([ID] int,[count] int)
insert [表1]
select 1,2 union all
select 2,3 union all
select 4,1 union all
select 5,4
--> 测试数据:[表2]
if object_id('[表2]') is not null drop table [表2]
create table [表2]([ID] int,[count] int)
insert [表2]
select 2,2 union all
select 3,3 union all
select 5,6 union all
select 7,1

select id,sum([count]) as [count] from(
select * from [表1]
union all 
select id,-[count] from [表2])a
group by id order by id asc
/*
id    count
1    2
2    1
3    -3
4    1
5    -2
7    -1
*/

------解决方案--------------------
SQL code
declare @t1 table(id int,count int)
insert into @t1
select 1,2 union all
select 2,3 union all
select 4,1 union all
select 5,4 
declare @t2 table(id int,count int)
insert into @t2
select 2,2 union all
select 3,3 union all
select 5,6 union all
select 7,1

select * from 
(select ID,COUNT from @t1 where id 
not in(select id from @t2)
union all
select ID,0-COUNT from @t2 where id 
not in(select id from @t1)
union all
select a.id,a.count-b.count 
from @t1 a join @t2 b on a.id=b.id) as a order by id

------解决方案--------------------
SELECT id,SUM(COUNT) FROM (
SELECT id,COUNT count FROM t1
UNION ALL
SELECT id,-COUNT count FROM t2
) b 
GROUP BY id