【问题标题】:Microsoft SQL - Return amount of male, female and total staff for each respective departmentMicrosoft SQL - 返回每个部门的男性、女性和总员工数量
【发布时间】:2020-06-06 01:43:28
【问题描述】:

我正在努力解决这个问题。

基本上,我需要做的是创建一个查询,该查询返回一个表,该表对每个部门的所有女性、男性和员工总数进行计数。

到目前为止,我已经能够显示所有部门以及女性、男性和员工的总数,但不能显示每个单独的部门(它显示每个部门的数量相同)。

如何只显示每个部门的男性、女性和员工总数??

问题和代码如下。以及代码产生的输出。

提前谢谢各位!

-- Username:
-- Q1004 For each of the different departments, show the number of current female, male and total
-- employees currently employed.
-- Schemas: HumanResources

-- Example output:
-- departmentName   female  male    totalEmployeeCount
-- Production        40     120         160

-- Write your query below


SELECT Name AS departmentName, 
(SELECT COUNT(gender) FROM AdventureWorksDB.HumanResources.Employee WHERE Gender = 'F') AS female,
(SELECT COUNT(gender) FROM AdventureWorksDB.HumanResources.Employee WHERE Gender = 'M') AS male,
(SELECT COUNT(gender) FROM AdventureWorksDB.HumanResources.Employee) AS totalEmployeeCount

FROM AdventureWorksDB.HumanResources.Department N 
JOIN AdventureWorksDB.HumanResources.EmployeeDepartmentHistory EDH 
ON N.DepartmentID = EDH.DepartmentID
JOIN AdventureWorksDB.HumanResources.Employee E
ON EDH.BusinessEntityID = E.BusinessEntityID
GROUP BY Name

输出看起来像这样

Department                female|male   |totalEmployeeCount
Engineering                84   |206    |290
Tool Design                84   |206    |290
Sales                      84   |206    |290
Marketing                  84   |206    |290
Purchasing                 84   |206    |290
Research and Development   84   |206    |290
Production                 84   |206    |290

【问题讨论】:

    标签: mysql sql ddl dml


    【解决方案1】:

    使用条件聚合:

    SELECT Name AS departmentName, 
           SUM(CASE WHEN e.gender = 'F' THEN 1 ELSE 0 END) as famale,
           SUM(CASE WHEN e.gender = 'M' THEN 1 ELSE 0 END) as male,
           COUNT(*) as totalEmployeeCount
    FROM AdventureWorksDB.HumanResources.Department N JOIN 
         AdventureWorksDB.HumanResources.EmployeeDepartmentHistory EDH 
         ON N.DepartmentID = EDH.DepartmentID JOIN
         AdventureWorksDB.HumanResources.Employee E
         ON EDH.BusinessEntityID = E.BusinessEntityID
    GROUP BY Name
    

    【讨论】:

      猜你喜欢
      • 2013-06-11
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2020-05-13
      • 2016-09-02
      • 2018-09-19
      • 1970-01-01
      • 2017-04-13
      相关资源
      最近更新 更多