gir*_*ake 3 sql inner-join adventureworks
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';
Run Code Online (Sandbox Code Playgroud)
但是,我试图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]
Run Code Online (Sandbox Code Playgroud)
我觉得我错过了一些明显的东西..
您可以使用条件聚合来做到这一点:
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
Run Code Online (Sandbox Code Playgroud)
但是你也可以用这种粗暴、直接的方式:
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'
Run Code Online (Sandbox Code Playgroud)
第一种方法当然是首选方法。
| 归档时间: |
|
| 查看次数: |
2117 次 |
| 最近记录: |