如何将两个 select 语句合并为一个 table 并有两个单独的列?

How can I combine two select statements into one table with two seperate columns?

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

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

尝试合并两个 SELECT 语句,每个语句包含 COUNT 男性和女性员工。 我可以使用 UNION ALL.

在同一 table 上将两个计数都计算到 return 两行
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';

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

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]

我觉得我遗漏了一些明显的东西..

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

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'

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