不使用分析函数来实现排名

问题描述:

我想知道是否有一种方法可以在不使用内置函数的情况下实现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; 
+0

我不想在mysql中这样做。 SELF JOIN会工作吗? – Teja

您可以使用相关的子查询来做到这一点。

select dept_id,salary, 
(select count(*) from emp e1 where e1.dept_id=e.dept_id and e1.salary>=e.salary) as rnum 
from emp e 

在没有关系的情况下,这很有效。

+0

工作正常...谢谢你...任何其他方法....你能解释一下sql的流程吗? – Teja

+0

如何在有领带时实施rownum? – Teja

+0

带领带的行号是密集的等级。 –

这里有三个等价表达式:

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”。

+0

如果有员工的薪水相同,那么rownum会失败。 – Teja

+0

喜欢你的解决方案,除了rownum ... – Teja

+0

@teja。 。 。无论是否有重复,这三项都应该有效。 'row_number()'依赖于表中唯一键的存在,如答案中所述。 –