日期:2014-05-18 浏览次数:21020 次
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([NeiRong] varchar(4),[xiangmu] varchar(4),[score] numeric(5,2))
insert [tb]
select '组织','财政',23.00 union all
select '组织','争部',30.00 union all
select '宣传','争部',50.00 union all
select '宣传','农村',10.00 union all
select '组织','党建',500.00 union all
select '宣传','党建',20.00
---查询---
declare @sql varchar(8000)
select
@sql=isnull(@sql+',','')
+'sum(case when xiangmu='''+xiangmu+''' then score else 0 end) as ['+xiangmu+']'
from
(select distinct xiangmu from tb) t
exec ('select NeiRong,'+@sql+' from tb group by NeiRong')
---结果---
NeiRong 财政 党建 农村 争部
------- --------------------------------------- --------------------------------------- --------------------------------------- ---------------------------------------
宣传 0.00 20.00 10.00 50.00
组织 23.00 500.00 0.00 30.00
(2 行受影响)
------解决方案--------------------
if object_id('tb')is not null
drop table tb
go
create table tb (neirong nvarchar(10),xiangmu nvarchar(10),socre decimal(10,2))
go
insert into tb select '组织','财政',23.00
union all select '组织','争部',30.00
union all select '宣传','争部',50.00
union all select '宣传','农村',10.00
union all select '组织','党建',500.00
union all select '宣传','党建',20.00
declare @str nvarchar(4000),@sql nvarchar(400)
set @str='select * from tb a pivot
(sum(socre) for xiangmu in ( '
set @sql=''
select @sql=@sql+',' +xiangmu from tb group by xiangmu
set @sql=stuff(@sql,1,1,'')
exec( @str+@sql+' )) b ')
/*
neirong 财政 党建 农村 争部
---------- --------------------------------------- --------------------------------------- --------------------------------------- ---------------------------------------
宣传 NULL 20.00 10.00 50.00
组织 23.00 500.00 NULL 30.00
(2 行受影响)
*/