关于网友提出的“ 求救!!这个SQL语句应该怎么写??”问题疑问,本网通过在网上对“ 求救!!这个SQL语句应该怎么写??”有关的相关答案进行了整理,供用户进行参考,详细问题解答如下:
问题: 求救!!这个SQL语句应该怎么写??
描述: 姓名 科目 成绩
zhang A 86.5
wang B 78
zhang B 77
li C 93.5
zhao D 58
zhao A 69.5
zhang C 73
wang C 80
li B 68.5
li D 90
zhang D 74
wang A 77.5
li A 43
zhao B 86
zhao C 100
wang D 70
如何通过上表生成zhang全部科目成绩的一个统计,如下:
科目 成绩 名次 前三名
A 86.5 1 zhang wang zhao
B 77 3 zhao wang zhang
C 73 4 zhao li wang
D 74 2 li zhang wang
求救!!这个SQL语句应该怎么写??
解决方案1: 试验中...
解决方案2: 这个要用到Cross Table了,将原本名字放到列上去哦.具体可以看看<>杨宗志 编着的书哦
解决方案3: --1.创建函数
create function f_str(@a1 varchar(10))
returns varchar(8000)
as
begin
declare @re varchar(8000)
set @re=''
select top 3 @re=@re+','+姓名 from table3 where 科目=@a1
return(stuff(@re,1,1,''))
end
--2.查询
declare @xm varchar(20)
set @xm='zhang'
select x.科目, @xm, (select 成绩 from table3 where 科目=x.科目 and 姓名=@xm) as 成绩,
(select count(*) +1 from table3 where 科目=x.科目 and 成绩>
(select 成绩 from table3 where 科目=x.科目 and 姓名=@xm)) as 名次, dbo.f_str(x.科目) as 前三名
from
(select distinct 科目 from table3) x
解决方案4: create table #temp(姓名 varchar(20), 科目 char, 成绩 float)
insert into #temp(姓名, 科目, 成绩)
select 'zhang', 'A', '86.5'
union all select 'wang' , 'B', '78'
union all select 'zhang' , 'B', '77'
union all select 'li' , 'C', '93.5'
union all select 'zhao' , 'D', '58'
union all select 'zhao' , 'A', '69.5'
union all select 'zhang' , 'C', '73'
union all select 'wang' , 'C', '80'
union all select 'li' , 'B', '68.5'
union all select 'li' , 'D', '90'
union all select 'zhang' , 'D', '74'
union all select 'wang' , 'A', '77.5'
union all select 'li' , 'A', '43'
union all select 'zhao' , 'B', '86'
union all select 'zhao' , 'C', '100'
union all select 'wang' , 'D', '70'
create table #排名表(科目 char, 成绩 float, 名次 int, 前三名 varchar(20))
insert into #排名表(科目, 成绩, 名次)
select 科目, 成绩,
(select count(t2.姓名) + 1 from #temp t2 where t2.科目 = t1.科目 and t2.成绩 > t1.成绩) as 名次
from #temp t1
where 姓名 = 'zhang'
declare @lessons varchar(255), @names varchar(255), @one_lesson char
set @lessons = ''
select @lessons = @lessons + ',' + 科目 from #排名表
while @lessons <> ''
begin
set @one_lesson = right(@lessons, 1)
set @names = ''
set nocount on
set rowcount 3
select @names = @names + ' ' + 姓名 from #temp where 科目 = @one_lesson order by 成绩 desc
set rowcount 0
set nocount off
update #排名表 set 前三名 = @names where 科目 = @one_lesson
set @lessons = left(@lessons, len(@lessons) - 2)
end
select * from #排名表
drop table #排名表
drop table #temp
解决方案5: select a.科目,a.成绩,
(select count(b.*) from tableA b where a.科目=b.科目 and b.成绩>=a.成绩) as 名次,
gettopstud(a.科目,3) as 前三名
from tableA a
where 姓名=zhang
//gettopstud你自己写个自定义函数,返回某个科目前几名的人员列表
解决方案6: 一条不行呀,要写存储过程了;
解决方案7: 一条语句估计是不行
写存储过程吧
以上介绍了“ 求救!!这个SQL语句应该怎么写??”的问题解答,希望对有需要的网友有所帮助。
本文网址链接:http://www.codes51.com/itwd/3243755.html