站点图标 江湖人士

早年用过的和写的一些SQL语句整理

早年用过的和写的一些SQL语句整理

学习SQL语句 group by

select stdname,
isnull(sum( case  stdsubject when  ' 化学 '  then Result end), 0 ) [化学],
isnull(sum( case  stdsubject when  ' 数学 '  then Result end), 0 ) [数学],
isnull(sum( case  stdsubject when  ' 物理 '  then Result end), 0 ) [物理],
isnull(sum( case  stdsubject when  ' 语文 '  then Result end), 0 ) [语文] 
from #student 
group by stdname

group by与sum + case结合,可以将表1中的记录(行)变成表2的字段(列)。Sum里面如果没有case,那么出来的值,只能是全部科目的总和,用了case以后,就是某科的成绩;然后这里用了好几个sum,每个科目一个sum,于是表1中本来某人某科占一条记录的“行”就变成了表2里某人一条记录,每科做一个字段了。

利用select from 写法生成SQL语句

declare @sql varchar( 4000 ) 
 set  @sql  =   ' select stdname ' 
 select @sql  =  @sql  +   ' ,isnull(sum(case stdsubject when  ''' + stdsubject + '''  then Result end),0) [ ' + stdsubject + ' ] ' 
 from (select distinct stdsubject from #student)  as  a 
 select @sql  =  @sql + '  from #student group by stdname ' 
 print @sql
 exec(@sql)
declare @sql varchar( 4000 ) 
 set  @sql  =   ' select stdname ' 
 select @sql  =  @sql  +   ' ,isnull(sum(case stdsubject when  ''' + stdsubject + '''  then Result end),0) [ ' + stdsubject + ' ] ' 
 from (select distinct stdsubject from #student)  as  a 
 select @sql  =  @sql + '  from #student group by stdname ' 
 print @sql
 exec(@sql)
select [name] into #tmpCloumns
from tempdb.dbo.syscolumns
where  id = object_id( ' tempdb.dbo.#student2 ' )
and [name] <> ' stdname '
select  *   from #tmpCloumns
  
declare @strSql nvarchar( 800 )
select @strSql = ''
select @strSql = @strSql + ' union all ' + char ( 10 ) + char ( 13 ) +
                 ' select [stdname], ''' + [name] + '''  as [科目],[ ' + [name] + ' ] ' + char ( 10 ) + char ( 13 ) +
                 ' from [#student2] ' + char ( 10 ) + char ( 13 )
from #tmpCloumns
 
select @strSql = substring(@strSql, 11 ,len(@strSql)) + ' order by stdname,[科目] '
exec(@strsql)

以上节选自网上一些贴子的SQL代码,很早以前看到的,原链接我不知道了。

退出移动版