2016-12-02 1 views
1

이 두 카운트 기능을 하나의 쿼리로 어떻게 얻을 수 있습니까?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'; 
+0

트릭은 'SUM'을 통해 'COUNT'을 (를) 구현하여 조건부 집계를 사용합니다. 'SUM (a = b THEN 1 ELSE 0 END) ' –

+0

컬럼 별명은 비표준 SQL입니다. 어떤 DBMS를 사용하고 있습니까? 표준 SQL에서는'count (*) filter (여기서 MaritalStatus = 'S '')'를 사용할 수 있습니다. –

답변

0

당신은 때 합계 케이스를 사용하여 시도 할 수 :

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 
0

당신은 group을 사용할 수 있으며 모두가 :

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

또는 당신이해야 MySQL과 decode

0

을 사용할 수 있습니다 직장 :

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이 아닌 다른 서버에서는 캐스트가 필요할 수 있습니다.

0

이러한 종류의 요청의 경우 집계 함수를 사용해야합니다. 이 같은

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()에 비해 이점을 사용하면 다른 결혼 상태를 추가하면 요청이 변경되지 않습니다.

0

다른 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 
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 
관련 문제