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

时间:2016-12-02 00:04:23

标签: 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';

6 个答案:

答案 0 :(得分:1)

您可以尝试在以下情况下使用总和案例:

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

答案 1 :(得分:1)

对于这种请求,您需要使用聚合函数。

SELECT MaritalStatus, COUNT(MaritalStatus)
FROM Person.Person PP
    INNER JOIN HumanResources.Employee HRE
        ON PP.BusinessEntityID = HRE.BusinessEntityID
GROUP BY MaritalStatus;

这将输出如下内容:

MaritalStatus  | COUNT(MaritalStatus)
               |
M              | 50
S              | 20

两排。你可以加 ORDER BY MaritalStatus以确保您按正确顺序接收数据,因为您收到数据的顺序不确定。

使用此优于SUM()的优点是,如果您添加其他婚姻状态,您的请求将不会更改。

答案 2 :(得分:1)

这也很有效,并且很容易扩展到其他MaritalStatuses。

SELECT married.*, single.* from
(   SELECT COUNT(MaritalStatus) as 'Married'
    FROM Person.Person PP INNER JOIN HumanResources.Employee HRE
    ON PP.BusinessEntityID = HRE.BusinessEntityID
    WHERE MaritalStatus = 'M'
    ) married
, (
    SELECT COUNT(MaritalStatus) as 'Single'
    FROM Person.Person PP INNER JOIN HumanResources.Employee HRE
    ON PP.BusinessEntityID = HRE.BusinessEntityID
    WHERE MaritalStatus = 'S'
    ) single

答案 3 :(得分:1)

由于from和join子句相同,只需将where条件移动到case语句中即可。

SELECT COUNT(case when MaritalStatus = 'M' then 1 end) as 'Married',
       COUNT(case when MaritalStatus = 'S' then 1 end) as 'Single'
FROM Person.Person PP 
JOIN HumanResources.Employee HRE
  ON PP.BusinessEntityID = HRE.BusinessEntityID

答案 4 :(得分:0)

您可以使用group并同时拥有:

SELECT COUNT(MaritalStatus) as 'Status'
    FROM Person.Person PP INNER JOIN HumanResources.Employee HRE
    ON PP.BusinessEntityID = HRE.BusinessEntityID
  group by MaritalStatus;

或者您可以使用decode

答案 5 :(得分:0)

使用MySQL,这应该有效:

SELECT SUM(MaritalStatus = 'M') as 'Married',
       SUM(MaritalStatus = 'S') as 'Single'
FROM Person.Person PP INNER JOIN HumanResources.Employee HRE
ON PP.BusinessEntityID = HRE.BusinessEntityID
WHERE MaritalStatus IN ('M', 'S');

(“MaritalStatus ='X')是一个布尔值,计算结果为0(假)或1(真)。在MySQL以外的其他服务器上,可能需要强制转换。