改一下,注('''+ box_id + ' ''then) 跟原业的区别:
create table #test (contract_number varchar(20),  box_id varchar(20),       box_num int)
go
insert into #test select '00电0634',          '01',              2 union all
select '00电0634',          '02-1',            1 union all
select '00电0634',          '02-2',            1 union all
select '00电0634',          '03' ,             3 union all
select '00电0988',          '01' ,             1 union all
select '00电0988',          '02' ,             1 union all select '00日0566',          '01',              2 union all
select '00日0566',          '02',              2 union all
select '00日0566',          '03' ,             2 union all
select '00日0567',          '01-1' ,           1 union all
select '00日0567',          '01-2' ,           1 union all 
select '00日0567',          '02' ,             2   go
declare @s varchar(8000)
set @s='' 
select @s=@s+',['+box_id+']=sum(case box_id when '''+ box_id + ' ''then box_num else 0 end)'
from (select distinct box_id=cast(box_id as varchar) from #test) aprint @s
exec('select contract_number'+@s+' from #test group by contract_number')
godrop table #test