每个部门仅选择一名员工

时间:2019-10-21 18:23:30

标签: sql sql-server tsql

My table schema and Data

我希望每个部门(EmpDepartment)都有一名员工,例如在我的表中有:

  • 3名拥有EmpDepartment 1的员工
  • 2名拥有EmpDepartment 2和
  • 的员工
  • 1名拥有EmpDepartment 3的员工

我希望每个独立部门的任何一名员工的EmployeeId,EmployeeName和EmpDepartment。

5 个答案:

答案 0 :(得分:1)

使用这样的窗口功能:

SELECT * FROM 
(
    SELECT EmployeeID, EmployeeName, EmployeeEmail
         , ROW_NUMBER() OVER (PARTITION BY EmpDepartment ORDER BY NEWID()) AS rn
    FROM   dbo.Employee
) x 
WHERE x.rn = 1

如果您有要用来挑选员工的业务规则,则可以在窗口功能中添加一个order子句

例如

SELECT *
FROM (
  SELECT 
     E.*,
     ROW_NUMBER() OVER (PARTITION BY EmpDepartment) AS RN
  FROM Employee
) X
WHERE X.RN = 1

答案 1 :(得分:0)

由于要通过NEWID()订购,因此每个部门都有一名随机雇员。

Optional<Node> wrappedNode1 = ((JavassistClassDeclaration) declaringType).toAst();

如果需要,可以将order by子句更改为其他内容。

答案 2 :(得分:0)

SELECT Top(1) EmployeeID, EmployeeName, EMPDeptartment  FROM Employee WHERE EmpDetpartment = 1

UNION

SELECT Top(1) EmployeeID, EmployeeName, EMPDeptartment  FROM Employee WHERE EmpDetpartment = 2

UNION

SELECT Top(1) EmployeeID, EmployeeName, EMPDeptartment  FROM Employee WHERE EmpDetpartment = 3

答案 3 :(得分:0)

这将返回该部门中具有最低EmployeeID的每个部门的员工(因为结果中哪个员工并不重要):

SELECT e.* FROM Employee e
WHERE NOT EXISTS (
  SELECT 1 FROM Employee 
  WHERE EmpDepartment = e.EmpDepartment AND EmployeeID < e.EmployeeID
)

答案 4 :(得分:-1)

您可以使用行号查找特定部门更改为1,2的任何员工,...等

Select department, employee
from (
   Select department, employee, 
      row_number() over (partition by department order by employee) rn
) 
where rn =1;

或使用简单分组依据

Select department, max(employee)
from table 
group by department