如何根据部门数量对员工数据进行排序

时间:2013-12-22 13:03:27

标签: sql-server

我有EMP表..
Eno Ename Salary deptmentid
101 Alex 2000 10

像这样,我有1000名员工的数据,有23个不同的部门。现在我的要求是以这样的方式对数据进行排序,即哪个部门最高的数量。员工..

例如,dept-50有45名员工(所有部门中最高),那么这45名员工应该首先列出。 Dept-12有3名员工,那么这3名员工应该列在雇员表中的最后一位。

4 个答案:

答案 0 :(得分:0)

尝试这样的事情,

Declare @Emp table ( Eno int, Ename varchar(50), Salary int, deptmentid int )

insert into @Emp values(1,'cvxcv',3,45),(2,'uyyudfdf',3,45),(3,'hhgcvxcv',3,45),(4,'wewecvxcv',3,46)
,(5,'sscvxcv',3,46),(6,'nmmcvxcv',3,47),(7,'erewr',3,47)

select *,dense_rank()over(order by deptmentid)rn from @Emp

答案 1 :(得分:0)

SELECT Eno, Ename, Salary, E.deptmentid
FROM EMP E INNER JOIN 
                (SELECT deptmentid, COUNT(Ename) TotalEmps  
                FROM EMP 
                GROUP BY deptmentid) Sub
ON E.deptmentid = Sub.deptmentid
ORDER BY TotalEmps DESC

答案 2 :(得分:0)

这是使用窗口功能的好机会:

select e.*
from (select e.*, count(*) over (partition by departmentmentid) as DepartmentCount
      from emp e
     ) e
order by DepartmentCount desc, DepartmentId;

请注意按DepartmentId排序以及计数。如果两个部门的计数相同,那么这将按部门将员工聚集在一起。

你也可能想:

select e.*, row_number() over (partition by departmentid order by newid()) as CounterInDepartment
. . .

这列举了每个部门的员工。

答案 3 :(得分:0)

select employee.name, employee.job, employee.deptmentid, 
    count(*)  over(partition by deptmentid) as [count]
 from EMPLOYEE
 order by [count] desc, deptmentid