SQL新手,使用带有AdventureWorks示例数据库的MS SQL Sever Management Studio:
尝试合并两个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';
但是我试图在两个单独的列中获得每个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]
我觉得我错过了一些明显的东西......
答案 0 :(得分:4)
您可以使用条件聚合执行此操作:
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'
第一种方法当然是首选方式。