2

我有一个表 emp 有以下数据:

EmpID    EmpName   MgrID 

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

现在我想显示这样的员工姓名(老板)和员工人数(下属)

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
4

2 回答 2

5
  • 从自我加入开始EmpID=MgrID
  • MgrID按和分组EmpName
  • 选择EmpNamecount(*)

将其转换为 SQL 是机械的:

SELECT b.EmpName, COUNT(*)
FROM Employee e
JOIN Employee b ON b.EmpID=e.MgrID
GROUP BY b.EmpID, b.EmpName
于 2012-07-10T18:22:53.650 回答
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
于 2012-07-10T18:31:08.043 回答