日期:2014-05-17 浏览次数:20930 次
declare @A table(名 nvarchar(2),量 int)
insert into @A
select N'苹果',5 union all
select N'草莓',4 union all
select N'香蕉',6 union all
select N'凤梨',2
declare @B table(人 nvarchar(2),名 nvarchar(2),量 int)
insert into @B
select N'甲',N'苹果',2 union all
select N'乙',N'香蕉',1 union all
select N'丙',N'草莓',3 union all
select N'丁',N'香蕉',5
;with cte as
(
select 名,sum(量) 量 from
(
select 名,量 from @A
union all
select 名,-sum(量) from @B group by 名
)t
group by 名
)
select * from
(
select * from @B
union all
select N'余',* from cte
where cte.量<>0
) t
order by charindex(','+名+',',N',苹果,草莓,香蕉,凤梨,'),charindex(','+人+',',N',甲,丙,乙,丁,余,')
/*
人 名 量
---- ---- -----------
甲 苹果 2
余 苹果 3
丙 草莓 3
余 草莓 1
乙 香蕉 1
丁 香蕉 5
余 凤梨 2
*/