搜索: 标题内容作者  
  首页数据库MSSQL
背景:
阅读新闻

SQL语句--行列转换以及字符串求和

[日期:2008-12-03]   来源:互联网整理  作者:佚名   [字体: ]
    新闻简介: create table tempAB(A varchar(10),B varchar(10))
        关 键 词:  
create table tempAB(A varchar(10),B varchar(10))
insert into tempAB values('a1','b1')
insert into tempAB values('a2','b1')
insert into tempAB values('a3','b1')
insert into tempAB values('a4','b2')
insert into tempAB values('a5','b2')
insert into tempAB values('a6','b2')

//新建一个表,以下代码可以返回B的值为b2,所有对应的A的值相加起来的结果
首先就是把A列中符合条件的行转换为列,col+A的值为列名,
再把各列相加

declare @sql varchar(4000)
set @sql = 'select '''''
select @sql=@sql+'+table'+A+'.'+'col'+A
from (select distinct A from tempAB where B='b2') as e
select @sql=@sql+' from '
select @sql=@sql+'(select a.'+'col'+A+' from(select (case A when '''+A+''' then A end) '+'col'+A+' '+
'from tempAB) a inner join (select (case A when '''+A+''' then A end) '+'col'+A+' '+
'from tempAB) b on a.col'+A+'=b.col'+A+') '+'table'+A+','
from (select distinct A from tempAB where B='b2') as f
select @sql=substring(@sql,0,len(@sql))
print @sql
exec(@sql)

If you believe an article violates your rights or the rights of others, please contact us.

收藏 推荐 打印 | 录入:admin | 阅读:
相关新闻      
友情链接
本文评论   [发表评论] 全部评论 (0)
赞助商广告
热门评论