如何计算SQL中不同表中的雇员人数?

时间:2019-02-18 19:10:08

标签: sql

问题问

“编写查询以显示办公室所在的城市和国家/地区以及该位置的雇员人数。按雇员人数的降序对结果进行排序。”

到目前为止,我已经提出,

SELECT city, country, SELECT COUNT(city,country) 
FROM Offices
ORDER BY(SELECT COUNT(city,country) 
                FROM Offices)DESC; 

但是我不能运行它。我认为我在SELECT COUNT部分中犯了一个错误。

employees表包含

  • employeeNumber
  • 姓氏
  • 名字
  • 扩展名
  • 电子邮件
  • 报告给
  • jobTitle
  • officeCode

Office表包含

  • officeCode
  • 城市
  • 电话
  • addressLine1
  • addressLine2
  • 状态
  • 国家
  • postalCode
  • 领土
  • officeLocation

有人知道我在做什么错吗?谢谢!抱歉,这是很多东西。

3 个答案:

答案 0 :(得分:0)

使用联接和计数

SELECT city, country,officeLocation, COUNT(e.employeeNumber) 
FROM Offices ofc join employees e on ofc.officeCode=e.officeCode
group by city, country,officeLocation

答案 1 :(得分:0)

解决此问题的几种方法。使用左外部联接:(请确保在此处使用左外部而不是INNER JOIN,否则您只会获得有员工的位置。在您的情况下可能会起作用,但是如果某个位置没有现有员工怎么办?)

SELECT City, Country, COUNT(e.employeeNumber) AS EmployeeCount
FROM Offices o
LEFT OUTER JOIN Employees e
    ON e.OfficeCode = o.OfficeCode
GROUP BY City, Country
ORDER BY 3 DESC

或者您可以在选择语句中使用子查询:

SELECT City, Country,
    (SELECT COUNT(*) FROM Employees e WHERE o.OfficeCode = e.OfficeCode) AS EmployeeCount
FROM Offices o
ORDER BY 3 DESC

答案 2 :(得分:0)

You can do it using a LEFT JOIN, GROUP BY and ORDER BY.
We need LEFT JOIN and GROUP BY to get the employee count and the ORDER BY to order the results in descending order of no of employees.

SELECT OfficeCode, City, Country, COUNT(E.employeeNumber) AS EmployeeCount
FROM Offices O
LEFT JOIN Employees E ON E.OfficeCode = E.OfficeCode
GROUP BY OfficeCode, City, Country
ORDER BY COUNT(E.employeeNumber) DESC