强大的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 (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)
复制代码 代码如下:
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代码,很早以前看到的,原链接我不知道了。