Home > Database > Mysql Tutorial > 学习SQL语句(强大的group by与select from模式)

学习SQL语句(强大的group by与select from模式)

WBOY
Release: 2016-06-07 18:02:54
Original
1020 people have browsed it

本文介绍的是强大的group by使用与利用select from (select from)的模式生成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 (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代码,很早以前看到的,原链接我不知道了。
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template