日期:2014-05-18  浏览次数:20452 次

急茬啊各位高手们 ... 先行谢过
表名CodeData:

InstCode code mValue
工商银行 余额 20
工商银行 贷款 30
建设银行 余额 40
建设银行 贷款 50

期望结果
 类型 工商银行 建设银行
余额 20 40
贷款 30 50


真心谢过 !

------解决方案--------------------
SQL code
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 行受影响)
**/