2

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

4

3 回答 3

1

您可以使用“ OLAP 表达式”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)表达式中指定的内容。

于 2013-09-09T22:20:26.537 回答
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 >= t1.ssn

sqlfiddle

数据:

数据

查询结果:

查询的结果

于 2013-09-09T18:40:34.650 回答
0
  select * from 
  ( select rank() over (partition by dptname  order by empname) as count , *
    from employees
  )
  where count<=2 
  order by deptname, ssn,name;
于 2013-12-31T05:54:24.343 回答