注册 登录
编程论坛 SQL Server论坛

请教个SQL语法

nixy 发布于 2007-08-17 08:16, 545 次点击
请教各位大虾:如何用语句把例表1的奖金汇总排列?
例表1
员工编号 奖金 年 月
108 48.9 2006 1
108 18.3 2006 1
108 140 2006 1
110 10 2006 1
110 1470 2006 1
110 11 2006 1
110 33 2006 1
102 45 2006 1
102 2 2006 1
102 42.5 2006 1
108 42.5 2006 2
102 70 2006 2
108 45 2006 4
108 2 2006 4
110 70 2006 4
102 50 2006 4
102 1470 2006 4
例表2
员工编号 1月 2月 3月 4月
108 奖金金额 奖金金额 奖金金额 奖金金额
110 奖金金额 奖金金额 奖金金额 奖金金额
102 奖金金额 奖金金额 奖金金额 奖金金额
2 回复
#2
wudi2513142007-08-18 15:48

create table ##Test (员工编号 int, 奖金 money, 年 int, 月 int)
insert ##Test
select 108, 48.9, 2006, 1 union all
select 108, 18.3, 2006, 1 union all
select 108, 140, 2006, 1 union all
select 110, 10, 2006, 1 union all
select 110, 1470, 2006, 1 union all
select 110, 11, 2006, 1 union all
select 110, 33, 2006, 1 union all
select 102, 45, 2006, 1 union all
select 102, 2, 2006, 1 union all
select 102, 42.5, 2006, 1 union all
select 108, 42.5, 2006, 2 union all
select 102, 70, 2006, 2 union all
select 108, 45, 2006, 4 union all
select 108, 2, 2006, 4 union all
select 110, 70, 2006, 4 union all
select 102, 50, 2006, 4 union all
select 102, 1470, 2006, 4

declare @sql varchar(8000)
set @sql = 'select 员工编号'
select @sql = @sql + ', ' + '[' + cast(月 as varchar) + '月] = sum(case 月 when ' + cast(月 as varchar) + ' then 奖金 else 0 end)' from ##Test group by 月
set @sql = @sql + ' from ##Test where 年 = 2006 group by 员工编号'

exec (@sql)
/*
员工编号1月2月4月
10289.500070.00001520.0000
108207.200042.500047.0000
1101524.0000.000070.0000
*/

drop table ##test
已经运行通过了

#3
nixy2007-08-18 18:10

谢谢

1