日期:2014-05-16 浏览次数:20704 次
select id,name,sum(amount) as amount from (
select id,name,amount from a
union all
select id,name,-amount from b
union all
select id,name,-amount from c)T
group by id,name
create table a(id int,name varchar(10),amount int)
insert a
select 1,'牙刷',30 union all
select 2,'牙膏',40 union all
select 3,'肥皂',50
create table b(id int,name varchar(10),amount int)
insert b
select 1,'牙刷',10 union all
select 2,'牙膏',10
create table c(id int,name varchar(10),amount int)
insert c
select 1,'牙刷',10
select a.id,
a.name,
a.amount-isnull(b.amount,0)-isnull(c.amount,0)
from a
left join b
on a.name=b.name
left join c
on a.name=c.name
/*
1 牙刷 10
2 牙膏 30
3 肥皂 50
*/