強大的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代碼,很早以前看到的,原鏈接我不知道了。