想要检查表中谁都是经理,以及经理下有多少人

时间:2019-10-09 07:05:32

标签: sql-server tsql

我在表中有4列:

emp_id  emp_name    job_name    manager_id
------------------------------------------
1        A          PRESIDENT     0
2        B          MANAGER       1
3        C          MANAGER       1
4        D          A M           1
5        E          A M           2
6        F          AM            2
7        G          AM            3

查询:

SELECT emp_name AS MANAGER 
FROM TABLE  
WHERE emp_id IN (SELECT manager_id FROM Table)

我正在使用此查询获取所有经理,但我还想查看谁在经理以下。

例如

MANAGER  SUM
-------------
A        3
B        2
C        1

我该如何求和?

1 个答案:

答案 0 :(得分:0)

添加COUNTGROUP BY,然后使用CTE。

;WITH cte AS (
SELECT
 manager_id
FROM
 table
GROUP BY
 manager_id
)
SELECT 
 t.emp_name AS MANAGER, 
 COUNT(t.emp_id) AS SUM
FROM 
 table as t
  INNER JOIN
 cte as c
  ON
   t.emp_id = c.manager_id
GROUP BY
 t.emp_name