数据库表如下:
部门表:(dept_id, dept_name)
员工表:(emp_id, emp_name, dept_id, come_in_date),dept_id是部门外键,come_in_date是进入该部门的日期能否通过一条SQL查出每个部门中最后进来的5个员工?
如果该部门中的员工数小于等于5个,则全部返回

解决方案 »

  1.   


    Sql Server:
        select top 5 e.* from tb_dept d inner join tb_emp e on d.dept_id = e.dept_id where d.dept='该部门' order by e.come_in_date desc    
    Oracle:
        select e.* from tb_dept d inner join tb_emp e on d.dept_id = e.dept_id where rownum<=5 and d.dept='该部门' order by e.come_in_date desc
      

  2.   

    partition  by 用这个组内排序进行筛选
      

  3.   

    好阿,请问下。
    select e.* from depart d,employee e where d.dept_id=e.dept_id and rownum<=5 and d.dept_id=3 order by e.com_in_date desc
    我这样写有跟用inner join有多大的差别呢?我是新手,一般都是用这种方式,不太习惯于用inner join这样的表连接。麻烦指点下哈。先谢谢咯
      

  4.   

    首先感谢楼上各位的回复,但不是满足要求的。
    我的意思是,能否用一条SQL查出每个部门中最后进来的5个员工,注意是每个部门,不是某个部门。
    比如举个例子,如果目前有3个部门,则最多只返回15条员工记录(也有可能会少于15条,因为其中某个部门下还不足5个员工)
    再次对你们的回复表示感谢。
      

  5.   

    select a.dept_id,a.emp_name,a.come_in_date
    from 员工表 a
    where (select count(distinct c.come_in_date) from 员工表 c where c.dept_id=a.dept_id and a.come_in_date<=c.come_in_date) <=5
    order by a.dept_id,a.come_in_date desc上面没有关联用部门表,只实现了你的关键需求(每个部门后五位进入员工)你只需把上面的sql加加工,关联一下部门表得到dept_name即可。
      

  6.   

     
    SELECT * FROM tb_emp AS a WHERE emp_id in (select top 5 emp_id from tb_emp where dept_id=a.dept_id order by come_in_date desc);  
      

  7.   

    或者是:
    oracle:
    select * from (
    select dept_id,emp_id, emp_name,come_in_date,dense_rank() over (partition by dept_id order by come_in_date desc)  order_no from tb_emp)
    where order_no <= 5;根据不同的需求,dense_rank() 可以用row_number()、rank( )、ntile( )(SQL Server)替代