计算主管的员工人数

时间:2013-11-24 17:06:35

标签: mysql sql

SELECT 
e.lname AS employee_name
, s.lname AS supervisor_name
, e.superssn AS supervisor_ssn
FROM employee e INNER JOIN employee s
WHERE e.superssn=s.ssn

我实际上有两个问题。第一个是,上面的声明工作得很好。但是现在它将向他们的主管展示一堆员工。组织不好。顺便说一下,有三个主管。有没有办法让员工A和主管B与员工B一起说出主管A等等?

第二个问题是我还试图计算每个主管的员工数量,而不是用COUNT()显示他们的名字,我尝试了几个不同的但没有工作。

1 个答案:

答案 0 :(得分:1)

一些事情

1)最好将连接谓词与连接保持一致。所以改变:

FROM employee e INNER JOIN employee s WHERE e.superssn = s.ssn

要:

FROM employee e INNER JOIN employee s ON e.superssn = s.ssn

2)要由主管将它们保持在一起,只需使用order by

SELECT 
  e.lname AS employee_name
  , s.lname AS supervisor_name
  , e.superssn AS supervisor_ssn
FROM employee e INNER JOIN employee s ON e.superssn = s.ssn
ORDER BY s.lname

3)要为每位主管计算员工数量,请使用group byCOUNT汇总功能

SELECT 
  s.lname AS supervisor_name,
  COUNT(*) AS employee_count
FROM employee e INNER JOIN employee s ON e.superssn = s.ssn
GROUP BY s.lname
ORDER BY s.lname