3

AdventureWorks サンプル DB で MS SQL Server Management Studio を使用する SQL の初心者:

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

それぞれが男性従業員と女性従業員SELECTを含む2 つのステートメントを結合しようとしています。COUNTUNION ALL を使用して、両方のカウントを取得して、同じテーブルの 2 つの行を返すことができます。

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 を 2 つの別々の列で取得しようとしています。2つの別々の列を表示することができましたが、カウントはありません。

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