积分排序解法2.txt
来自「SQL语言常用的一些命令各代码」· 文本 代码 · 共 75 行
TXT
75 行
/*
表A
姓名 科目 分数
---------------------------------
张三 语文 88
张三 数学 90
张三 政治 90
李四 语文 90
李四 数学 92
王五 语文 70
王五 数学 80
刘二 语文 90
刘二 政治 73
-----------------------------
生成报表如下:
姓名 语文名次 数学名次 政治名次 总分名次
张三 3 2 1 2
李四 1 1 1
王五 1 3 3
刘二 4 3 4
*/
CREATE FUNCTION sort(
@oname varchar(10)
,@otype varchar(10)
)RETURNS int
AS
BEGIN
declare @id int,@score int,@score1 int
set @id=0
set @score=0
set @score1=0
select @score1=score from tb where otype=@otype and oname=@oname
select @id=case when score>=@score1 then @id+1 else @id+0 end from tb where otype=@otype
order by score desc
RETURN @id
END
go
drop table tb
create table tb
(
oname varchar(50)
,
otype varchar(50)
,
score int
)
insert into tb(oname,otype,score)
select '张三','语文',88
union all
select '张三','数学',100
union all
select '张三','政治',100
union all
select '李四','语文',90
union all
select '李四','数学',92
union all
select '王五','语文',70
union all
select '王五','数学',80
select oname,sum(case when otype='语文' then dbo.sort(oname,'语文') end ) as 语文名次,
sum(case when otype='数学' then dbo.sort(oname,'数学') end ) as 数学名次,
sum(case when otype='政治' then dbo.sort(oname,'政治') end ) as 政治名次
from tb
group by oname
order by oname
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?