日期:2014-05-17 浏览次数:20511 次
if OBJECT_ID('tempdb..#tempA', 'u') is not null drop table #tempA;
go
create table #tempA( [ID] varchar(100), [姓名] varchar(100));
insert #tempA
select '001','张三' union all
select '002','李四'
if OBJECT_ID('tempdb..#tempB', 'u') is not null drop table #tempB;
go
create table #tempB( [ID] varchar(100), [区分] varchar(100), [金额] INT);
insert #tempB
select '001','工资','8000' union all
select '001','奖金','3000' union all
select '002','工资','7000' union all
select '002','奖金','2500'
--SQL:
SELECT a.姓名,
总额 = SUM(b.金额),
奖金 = SUM(CASE b.区分 WHEN '奖金' THEN b.金额 ELSE 0 END)
from #tempA a
INNER JOIN #tempB b
ON a.id = b.id
GROUP BY a.id, a.姓名
/*
张三 11000 3000
李四 9500 2500
*/