考试辅导

名师推荐

试听名师的课 查看所有名师

计算机等级考试辅导:SQL语句(行列转换及字符串求和) 发布时间:2010-07-02 17:29 来源:互联网

  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)

第一考试网友情提示:如果您遇到任何疑问,请登录第一考试网考试辅导频道或添加qq:,第一考试网以“为考友服务”为宗旨,秉承“快乐学习,轻松考试!”的理念,旨在为广大考友打造一个良好、温馨的学习与交流平台,欢迎持续关注。以上是小编为大家推荐的《计算机等级考试辅导:SQL语句(行列转换及字符串求和)》相关信息。

编辑推荐

计算机等级考试辅导:SQL中JOB的运行状态

计算机等级考试辅导:SQLSERVER2005的引用

三级:把数据导入不同的表空间

2009年三级信息管理技术辅导:战略数据规划

教你三种方法卸载Windows7SP1Beta