日期:2014-05-18 浏览次数:20570 次
--> 测试数据:[表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 */
------解决方案--------------------
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