系统中提出新的需求,需求分析计算考生与上次考试成绩的分差,判断成绩提升是否过大:
数据如下:
ID Name Score Date
340321198611285950 吴赞赞 73.10 20080415
340321198611285950 吴赞赞 70.00 20080617
340321198611285950 吴赞赞 77.25 20080813
340321198611285950 吴赞赞 74.95 20090216
340321198611285950 吴赞赞 77.65 20090401
340321198611285950 吴赞赞 75.70 20090907
同一个ID在不同时间进行了多次考试,假如查询条件查询出来的结果为20090401的这条记录,要求计算出与上一次考试成绩(也就是20090216这次)的分差.
先按照日期排序,然后通过连接或者子查询,查询两次成绩的差,然后做统计~
直译:
declare @scr decimal(18,2)//当前分数
declare @preScr decimal(18,2)//上一次分数
declare @rn int//当前分数记录行数
set @scr = 0
set @preScr = 0
set @rn = 0
select @scr = isnull(Score,0),@rn=isnull(rn,0) from (select Score,row_number() over(order by Date desc) as rn from tb where Date = 20090401) as a
select @preScr = isnull(Score,0) from (select Score,row_number() over(order by Date desc) as rn from tb) as b where b.rn = @rn + 1
select @scr - @preScr
declare @scr decimal(18,2)//当前分数
declare @preScr decimal(18,2)//上一次分数
declare @rn int//当前分数记录行数
set @scr = 0
set @preScr = 0
set @rn = 0
if(exists(select count(1) from tb where Date = 20090401))
begin
select @scr = isnull(Score,0),@rn=isnull(rn,0) from (select Score,row_number() over(order by Date desc) as rn from tb where Date = 20090401) as a
select @preScr = isnull(Score,0) from (select Score,row_number() over(order by Date desc) as rn from tb) as b where b.rn = @rn + 1
end
else
begin
--其他处理
end
select @scr - @preScr
一楼说得很清楚了,2楼的太复杂了。