2016-10-21 5 views
0
내가 그룹화와 두 개의 부울 열

SQL은 부울 필드

에 의해 비는 그룹화 일부 럼의 구별 발생을 계산 할

에 의해 별개의 그룹

select count(Distinct some_column) as Uniques, sum(some_other_col) 
from myTable T 
where T.created_at>'2016-09-15' 
group by T.col1, T.col2 

이 쿼리는 네 개의 값

uniques when col1=true and col2=true 
uniques when col1=true and col2=false 
uniques when col1=false and col2=true 
uniques when col1=false and col2=false 

가 있습니다 동일한 쿼리를 변경하고이 세 가지 값을 가져올 수 있습니까? 내가 처음 4 개 개의 값

uniques (all) 
uniques when col1=true 
uniques when col2=true 

UPDATE

는 사실 내가 합계를 얻을 다른 값이 있기 때문에하여 그룹을 유지하려면를 결합하는 정보를 얻을 수 없습니다.

답변

2

사용 조건 집합 :

select count(Distinct some_column) as Uniques, 
     count(distinct case when t.col1 then some_column end) as Uniques_col1_true, 
     count(distinct case when t.col2 then some_column end) as Uniques_col2_true 
from myTable t 
where t.created_at > '2016-09-15'; 
+0

감사를 사용해보십시오. 이게 나에게 7 개의 숫자를 줄 것인가? – albert

+0

@albert. . . 아닙니다. 당신이 요구하는 세가지를 제공합니다. 그러나 조건을 추가하여 원하는 모든 값을 얻을 수 있습니다. –

0

SELECT SUM(CASE WHEN col1 = TRUE 
      AND col2 = TRUE THEN 1 ELSE 0 END) AS opt1, 
     SUM(CASE WHEN col1 = TRUE 
      AND col2 = FALSE THEN 1 ELSE 0 END) AS opt2, 
FROM 
    (SELECT DISTINCT col1, 
        col2, 
        somecolumn 
    FROM TABLE T 
    WHERE ...) AS TB