读书人

急茬啊 . 先行谢过

发布时间: 2012-06-01 16:46:36 作者: rapoo

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

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

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


真心谢过 !

[解决办法]

SQL code
if object_id('[CodeData]') is not null drop table [CodeData]gocreate table [CodeData]([InstCode] varchar(8),[code] varchar(4),[mValue] int)insert [CodeData]select '工商银行','余额',20 union allselect '工商银行','贷款',30 union allselect '建设银行','余额',40 union allselect '建设银行','贷款',50godeclare @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) texec ('select code as 类型,'+@sql+' from CodeData group by code')/**类型   工商银行        建设银行---- ----------- -----------贷款   30          50余额   20          40(2 行受影响)**/ 

读书人网 >SQL Server

热点推荐