每个部门只选择两名员工

时间:2013-09-09 18:37:50

标签: db2

您能告诉我如何从每个部门只选择两名员工吗?该表有deptname,ssn,name。我正在进行抽样,每个部门名称只需要两个ssns。有人可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

您可以使用“OLAP expression”row_number()

来完成此操作
  with e as
  ( select deptname, ssn, empname,
           row_number() over (partition by dptname  order by empname) as pick
      from employees
  )
  select deptname, ssn, empname
    from e
    where pick < 3
    order by deptname, ssn

此示例将为您提供具有最低订单名称的两名员工,因为这是row_number() (order by)表达式中指定的内容。

答案 1 :(得分:0)

试试这个:

select *
from   t t1
where (
  select  count(*) 
  from t t2
  where 
    t2.deptname = t1.deptname 
    and 
    t2.ssn <= t1.ssn) <= 2 
order by deptname, ssn,name;

以上将给出“最小的”两个ssn。

  

如果您想要前2名,请更改为t2.ssn&gt; = t1.ssn

sqlfiddle

数据:

the data

来自查询的结果:

the result from query

答案 2 :(得分:0)

  select * from 
  ( select rank() over (partition by dptname  order by empname) as count , *
    from employees
  )
  where count<=2 
  order by deptname, ssn,name;