2016-12-07 75 views
0

我有2表:如何在SQL中应用以下情况下的条件聚合?

  1. tbDepatrment 2. tbEmployee

结果所需要的:

Department  Employees(by department) Male(By department)  Female(by department) 
Employee   11       6       5 
Management  10       5       5 
Owner   1        1       0 

我用这个:

SELECT [tbDepartment].[DepartmentName] AS [Department name], 
     Count(*) AS [Number of employees by department type], 
     (Select Count([EmployeeGender]) FROM [tbEmployee] WHERE [EmployeeGender] = 'Male' AND [DepartmentName] = [tbDepartment].[DepartmentName]) AS [Number of male employees by department type], 
     (Select Count([EmployeeGender]) FROM [tbEmployee] WHERE [EmployeeGender] = 'Female' AND [DepartmentName] = [tbDepartment].[DepartmentName]) AS [Number of female employees by department type] 
FROM [tbEmployee] JOIN [tbDepartment] 
ON [tbEmployee].[DepartmentId] = [tbDepartment].[DepartmentId] 
GROUP BY [tbDepartment].[DepartmentName]; 

导致为:

Department  Employees(by department) Male(By department)  Female(by department) 
Employee   11       12       10 
Management  10       12       10 
Owner   1        12       10 

如何根据第1列或按列分组显示第3列和第4列?

+0

请看看[怎么问](http://stackoverflow.com/help/how-to-ask) – swe

+0

@swe我改变了我的问题..如果仍然需要改进改变它或建议我。 –

回答

3

您不需要子查询来计算男性和女性的数量。相反,使用CASE表达式与条件聚合。

SELECT [tbDepartment].[DepartmentName] AS [Department name], 
    COUNT(*) AS [Number of employees by department type], 
    SUM(CASE WHEN [EmployeeGender] = 'Male' THEN 1 ELSE 0 END) AS [Number of male employees by department type], 
    SUM(CASE WHEN [EmployeeGender] = 'Female' THEN 1 ELSE 0 END) AS [Number of female employees by department type] 
FROM [tbEmployee] JOIN [tbDepartment] 
    ON [tbEmployee].[DepartmentId] = [tbDepartment].[DepartmentId] 
GROUP BY [tbDepartment].[DepartmentName]; 

更新:

虽然上面我在回答有条件的聚集是去这里,其实我不知道为什么你的子查询被赋予了错误的输出方式。你得到的输出是所有部门中男性和女性的总数,针对每个部门。你所得到的输出将与形式的子查询是一致的:

SELECT COUNT([EmployeeGender]) 
FROM [tbEmployee] 
WHERE [EmployeeGender] = 'Male' 

没有部门检查。也许你应该检查你的原始查询,看看它是否与你在这里发布的内容相符。

+0

更新:我检查了它。它给男性和完整表的女性,不系带型(不远处的各部门)过滤的总数。 –