SQL:单个查询中有两个计数函数?

标签 sql

如何将这两个计数函数放入一个查询中?

SELECT 
    COUNT(MaritalStatus) as 'Married'
FROM 
    Person.Person PP 
INNER JOIN 
    HumanResources.Employee HRE ON PP.BusinessEntityID = HRE.BusinessEntityID
WHERE 
    MaritalStatus = 'M';

SELECT 
    COUNT(MaritalStatus) as 'Single'
FROM 
    Person.Person PP 
INNER JOIN 
    HumanResources.Employee HRE ON PP.BusinessEntityID = HRE.BusinessEntityID
WHERE 
    MaritalStatus = 'S';

最佳答案

您可以在以下情况下尝试使用总和大小写:

SELECT SUM(CASE WHEN MaritalStatus = 'M' THEN 1 ELSE 0 END), 
SUM(CASE WHEN MaritalStatus = 'S' THEN 1 ELSE 0 END) 
FROM Person.Person PP INNER JOIN HumanResources.Employee HRE
ON PP.BusinessEntityID = HRE.BusinessEntityID

关于SQL:单个查询中有两个计数函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40922612/

相关文章:

php - 如何通过触发器使用服务器发送的事件?

mysql - MySQL 中何时使用单引号、双引号和反引号

MySQL 数据库 INNER 连接 - 查询帮助

mysql - 选择mysql中所有 parent 记录

mysql - 创建 SQL 查询时遇到问题

mysql - 使用SQL获取具有相同id的最高项目

带有 group by 和 having 子句的 Mysql 查询

mysql - 我可以从 SQL DB 模式在 Symfony2 中构建实体吗?

SQL Server 2008 Standard,获取包含所有列的所有表以及列中可能的数据

mysql - 打印存储过程中插入中使用的变量列表