SQL 新手,使用 MS SQL Sever Management Studio 和 AdventureWorks 示例数据库:
试图合并两个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]
我觉得我错过了一些明显的东西..