Sunday, May 5, 2013

The Biggest Sql statement which i used..

This is the biggest query i used during my development life up to now.this query retrieves students with their ranks.when two students got same marks they are having same rank and next person will be 1 after their rank.so this query gives practical ranking functionality.


set @totalS = 0;
select count(*) into @totalS from exammarks;
SELECT exammarks.stdid, (exammarks.Test1 + exammarks.Test2 + exammarks.Test3 + exammarks.Test4)/4 AS avge, @curRank :=
IF(@prevVal=(exammarks.Test1 + exammarks.Test2 + exammarks.Test3 + exammarks.Test4)/4, @curRank, @studentN) AS rank,
@percentile := IF(@prevVal=(exammarks.Test1 + exammarks.Test2 + exammarks.Test3 + exammarks.Test4)/4, @percentile,
(@totalS - @studentN + 1)/(@totalS)*100) as percent,
@studentN := @studentN + 1 as studentN,
@prevVal:=(exammarks.Test1 + exammarks.Test2 + exammarks.Test3 + exammarks.Test4)/4 as totagain
FROM exammarks, (
SELECT @curRank :=0, @prevVal:=null, @studentN:=1, @percentile:=100
) r
ORDER BY (exammarks.Test1 + exammarks.Test2 + exammarks.Test3 + exammarks.Test4)/4 DESC

No comments:

Post a Comment