如何将两个select语句组合成一个具有两个单独列的表?

时间:2015-11-06 06:42:58

标签: sql inner-join adventureworks

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

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';

但是我试图在两个单独的列中获得每个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]

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

1 个答案:

答案 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'

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