设有一表存有某班N个学生的数学成绩表,表结构如下:
姓名 分数
aaa 89
bbb 70
. .
. .
. .
现需以下结果:
-----------------------------------------------
不及格学生 60-80分 80-100分
-----------------------------------------------
姓名 分数 姓名 分数 姓名 分数
fff 55 bbb 70 aaa 89
---------------------------------------------------------------
下面的语句更合理一些:
declare @a int,@b int
select identity(int) id0,name,score into #temp1 from test1
where score <60 order by name; --不及格
select identity(int) id0,name,score into #temp2 from test1
where score >=60 and score <80 order by name; --60~80
select identity(int) id0,name,score into #temp3 from test1
where score >=80 and score <=100 order by name; --80~100
select @a = count() from #temp1
select @b = count() from #temp2
if (@a > @b)
select a.name,a.score,b.name,b.score,c.name,c.score from #temp1 a
full outer join #temp2 b on a.id0 = b.id0
full outer join #temp3 c on a.id0 = c.id0
else
select a.name,a.score,b.name,b.score,c.name,c.score from #temp1 a
full outer join #temp2 b on a.id0 = b.id0
full outer join #temp3 c on b.id0 = c.id0
drop table #temp1,#temp2,#temp3
太晚了,我要回家了。
---------------------------------------------------------------
To IronPromises(铁诺):
我的方法和你第一次使用的方法差不多(一样)
drop table #temp1,#temp2,#temp3
select identity(int,1,1) as ID,Name,Score into #temp1 from Test where Score<60
select identity(int,1,1) as ID,Name,Score into #temp2 from Test where Score>=60 and Score<80
select identity(int,1,1) as ID,Name,Score into #temp3 from Test where Score>=80 and Score<=100
select A.Name,A.Score,B.Name,B.Score,C.Name,C.Score
from #temp1 A full outer join #temp2 B on A.ID=B.ID
full outer join #temp3 C on B.ID=C.ID
不过你第二次的IF语句就有点糊涂了~,既然执行的语句都一样,那还判断
@a、@b的大小干什么?