如何在SQL中的同一列中有两个COUNT个查询GROUPED?

时间:2016-10-24 04:57:14

标签: sql

我有两个名为Employees的表,一个名为Shop。 Employees表保存所有员工的性别,而Shop表具有每个员工工作的商店的名称。

我需要计算男性和女性员工的数量,并将他们分组到他们工作的商店。例如,想要的结果将如下所示:

FemaleEmployees MaleEmployees Store 1 2 Ed's Hardware 3 4 Grocery store

到目前为止,我有这个:

SELECT COUNT(Gender) AS FemaleEmployees, StoreName AS Store
FROM Employees 
JOIN Store
ON Employees.EmployeeID = Store.EmployeeID
Where Gender = 'F'
GROUP BY StoreName;

SELECT COUNT(Gender) AS MaleEmployees, StoreName AS Store
FROM Employees
JOIN Store
ON Employees.EmployeeID = Store.EmployeeID
Where Gender = 'M'
GROUP BY StoreName;

这显然在两个选择查询中提供了所需的答案,但我需要它在一个查询中。我只需要帮助将两者合并为一种查询格式。

我已经尝试过使用两个subquerys,但到目前为止还没有任何效果。我知道如何得到答案,而不是所需的格式。如果有人能帮我解决这个问题,我将不胜感激。

4 个答案:

答案 0 :(得分:5)

你可以这样做

SELECT SUM(CASE WHEN Gender='F' THEN 1 ELSE 0 END) As FemaleEmployees,
       SUM(CASE WHEN Gender='M' THEN 1 ELSE 0 END) As MaleEmployees,
       storeName
FROM Employees 
JOIN Store
ON Employees.EmployeeID = Store.EmployeeID
GROUP BY storeName

答案 1 :(得分:4)

使用COUNT

的另一种方法
SELECT COUNT(CASE WHEN Gender='F' THEN 1 END) As FemaleEmployees,
       COUNT(CASE WHEN Gender='M' THEN 1 END) As MaleEmployees,
       StoreName AS Store
FROM Employees 
JOIN Store
ON Employees.EmployeeID = Store.EmployeeID
Where Gender in ( 'F','M' )
GROUP BY StoreName;

过滤Gender子句中的Where,使查询效率不高..

答案 2 :(得分:0)

你需要使用“case”语句来区分这些情况,如下所示: SELECT SUM (SELECT CASE WHEN GENDER = 'M' THEN 1 ELSE 0 END) as MaleCount, SUM (SELECT CASE WHEN GENDER = 'F' THEN 1 ELSE 0 END) AS FemaleCount, Storename AS Store FROM Employees JOIN Store ON Employees.EmployeeID = Store.EmployeeID

GROUP BY StoreName;

GROUP BY StoreName;

答案 3 :(得分:0)

以上大多数答案总是得到性别1或0的计数......没有得到实际数量.. 因此,你可以做到这一点......

选择(如果GENDER =' M'那么COUNT(GENDER)ELSE 0 END)作为MaleCount, (例如,当性别=' F'那么(COENDER)ELSE 0 END)作为FemaleCount,  Storename AS Store     来自员工     加入商店     ON Employees.EmployeeID = Store.EmployeeID GROUP BY StoreName;