在SQL中显示员工姓名(Boss)和员工(下属)的数量

时间:2012-07-10 18:16:46

标签: sql sql-server sql-server-2008 join

我有一个表emp有foll数据:

EmpID    EmpName   MgrID 

100     King        NULL
101     Smith       100
102     Shine       100
103     Racy        102

现在我要显示员工姓名(Boss)和员工(下属)的数量

BOSS       SUBORDINATES

BLAKE                 5

CLARK                 1

FORD                  1

JONES                 2

KING                  3

SCOTT                 1

请指导如何在SQL Server 2008中查询此表。

尝试查询:

select e.first_name as ename,m.first_name as mname from employees e,employees m where e.manager_id=m.employee_id

2 个答案:

答案 0 :(得分:5)

  • 首先在EmpID=MgrID
  • 上自行加入
  • MgrIDEmpName
  • 分组
  • 选择EmpNamecount(*)

将其翻译为SQL是机械的:

SELECT b.EmpName, COUNT(*)
FROM Employee e
JOIN Employee b ON b.EmpID=e.MgrID
GROUP BY b.EmpID, b.EmpName

答案 1 :(得分:1)

CREATE TABLE test (
   EmpID INT,
   EmpName VARCHAR(100),
   MgrID INT)

INSERT INTO test VALUES (100, 'King', NULL),
                        (101, 'Smith', 100),
                        (102, 'Shine', 100),
                        (103, 'Racy', 102)

SELECT t1.EmpName AS Boss, 
       COUNT(*) AS Subordinates
FROM test AS t1 INNER JOIN test AS t2 ON t1.EmpID = t2.MgrID
GROUP BY t1.EmpName