这地方的排名分为并列排名 先看sql
方式一:
select s1.emp_no,s1.salary,count(distinct s2.salary)
from salaries as s1 ,salaries as s2
where s1.to_date='9999-01-01'
and s2.to_date='9999-01-01'
and s1.salary<=s2.salary
group by s1.emp_no,s1.salary
order by s1.salary desc,s1.emp_no asc
方式二:
select s.emp_no ,s.salary,
case
when @rowtotal = s.salary then
@rank
when @rowtotal := s.salary then
@rank := @rank+1
when @rowtotal:=0 then
@rank:=@rank+1
END as rank from salaries s , (SELECT @rank := 0 ,@rowtotal := NULL) r where s.to_date = '9999-01-01' ORDER BY s.salary desc,s.emp_no asc
非并列排名:
select s.emp_no,s.salary ,@curRank := @curRank + 1 AS rank
from salaries s,(SELECT @curRank := 0) t where s.to_date = '9999-01-01' ORDER BY s.salary desc
:= 与 = 区别
=
只有在set和update时才是和:=一样,赋值的作用,其它都是等于的作用。鉴于此,用变量实现行号时,必须用:=
:=
不只在set和update时时赋值的作用,在select也是赋值的作用。