我要查询每个部门工资前3名的怎么写sql?

解决方案 »

  1.   

    SELECT
    b.*
    FROM (SELECT DISTINCT bumen FROM staff) AS a
    CROSS APPLY(SELECT TOP 3 * FROM staff WHERE bumen=a.bumen ORDER BY salary desc) AS b
      

  2.   

    或SELECT * FROM (SELECT *,ROW_NUMBER()OVER(PARTITION BY bumen ORDER BY salary DESC) AS RN FROM staff) AS t WHERE RN<=3
      

  3.   

    上面一个部门只显示<=3位,当salary相同时,要并列连续或断时
    可用DENSE_RANK/RANK
      

  4.   

    这个是oracle的吗,我在mysql运行不了。
      

  5.   


    mysql中要先排号,然后再把前3个取出来 。
      

  6.   

    MYSQL 
    e.g.select * from (select *,@id:=if(`bumen`=@bumen,@id+1,1) as RN,@bumen:=`bumen` from J1 order by bumen,salary desc) as t where RN<=3 ;
      

  7.   

    SELECT * FROM (SELECT *,ROW_NUMBER()OVER(PARTITION BY bumen ORDER
      

  8.   

    select a.* from t1 left t2 on t1.bumen=t2.bumen and t1.salary < t2.salary group by t1.name,t1.bumen,t1.salary having count(1)<3
      

  9.   

    select * from staff a
    where 3>(select count(1) from staff where bumen=a.bumen and salary<a.salary)
    ORDER BY a.salary desc
      

  10.   

    select * from staff a
    where 3>(select count(1) from staff where bumen=a.bumen and salary>a.salary)
    ORDER BY a.salary desc
      

  11.   

    参考下贴中的多种方法http://blog.csdn.net/acmain_chm/article/details/4126306
    [征集]分组取最大N条记录方法征集,及散分....