不使用分析函数来实现排名
问题描述:
我想知道是否有一种方法可以在不使用内置函数的情况下实现SQL分析函数。有人可以帮我弄这个吗。谢谢。不使用分析函数来实现排名
SELECT *,
ROW_NUMBER() OVER(PARTITION BY dept_id ORDER BY salary DESC) AS rownum,
DENSE_RANK() OVER(PARTITION BY dept_id ORDER BY salary DESC) AS denserank,
RANK() OVER(PARTITION BY dept_id ORDER BY salary DESC) AS rnk
FROM emp;
答
这里有三个等价表达式:
select emp.*,
(select count(*)
from emp emp2
where emp2.dept_id = emp.dept_id and
(emp2.salary > emp.salary or
emp2.salary = emp.salary and emp2.emp_id <= emp.emp_id
)
) as "row_number",
(select 1 + count(*)
from emp emp2
where emp2.dept_id = emp.dept_id and
emp2.salary > emp.salary
)
) as "rank",
(select count(distinct salary)
from emp emp2
where emp2.dept_id = emp.dept_id and
emp2.salary >= emp.salary
) as "dense_rank",
from emp;
这是假设一个emp_id
的存在,使行唯一的“ROW_NUMBER”。
我不想在mysql中这样做。 SELF JOIN会工作吗? – Teja