日期:2014-05-18 浏览次数:20610 次
if object_id('[CodeData]') is not null drop table [CodeData]
go
create table [CodeData]([InstCode] varchar(8),[code] varchar(4),[mValue] int)
insert [CodeData]
select '工商银行','余额',20 union all
select '工商银行','贷款',30 union all
select '建设银行','余额',40 union all
select '建设银行','贷款',50
go
declare @sql varchar(8000)
select
@sql=isnull(@sql+',','')
+'sum(case when InstCode='''+InstCode+''' then mValue else 0 end) as ['+InstCode+']'
from
(select distinct InstCode from CodeData) t
exec ('select code as 类型,'+@sql+' from CodeData group by code')
/**
类型 工商银行 建设银行
---- ----------- -----------
贷款 30 50
余额 20 40
(2 行受影响)
**/