3

SQL 新手,使用 MS SQL Sever Management Studio 和 AdventureWorks 示例数据库:

http://elsasoft.com/samples/sqlserver_adventureworks/sqlserver.spring.katmai.adventureworks/default.htm

试图合并两个SELECT语句,每个语句都包含一个COUNT男性和女性员工。我可以使用 UNION ALL 获得两个计数以在同一个表上返回两行。

SELECT COUNT(HumanResources.Employee.Gender) AS 'Male Employees' 
FROM HumanResources.Employee
WHERE Employee.Gender = 'M'
UNION ALL
SELECT COUNT(HumanResources.Employee.Gender) AS 'Female Employees' 
FROM HumanResources.Employee
WHERE Employee.Gender = 'F';

但是,我试图COUNT在两个单独的列中获取每个 M/F 的值。设法让两个单独的列出现,但计数不存在。

SELECT Set1.[Male Employees], Set2.[Female Employees]
FROM
(   
    SELECT COUNT(Employee.Gender) AS 'Male Employees' 
    FROM HumanResources.Employee
    WHERE Employee.Gender = 'M'
    ) as Set1
INNER JOIN
(
    SELECT COUNT(Employee.Gender) AS 'Female Employees' 
    FROM HumanResources.Employee
    WHERE Employee.Gender = 'F'
) as Set2
on Set1.[Male Employees] = Set2.[Female Employees]

我觉得我错过了一些明显的东西..

4

1 回答 1

5

您可以使用条件聚合来做到这一点:

SELECT SUM(CASE WHEN Employee.Gender = 'M' THEN 1 ELSE 0 END) AS 'Male Employees',
       SUM(CASE WHEN Employee.Gender = 'F' THEN 1 ELSE 0 END) AS 'Female Employees'  
FROM HumanResources.Employee

但您也可以采用这种残酷、直接的方式:

SELECT (SELECT COUNT(HumanResources.Employee.Gender)
        FROM HumanResources.Employee
        WHERE Employee.Gender = 'M') AS 'Male Employees',
       (SELECT COUNT(HumanResources.Employee.Gender) 
        FROM HumanResources.Employee
        WHERE Employee.Gender = 'F') AS 'Female Employees'

第一种方法当然是首选方法。

于 2015-11-06T06:47:54.350 回答