2009-08-24 4 views
4

MySQL은 같은 테이블에서 통합 쿼리에 :어떻게 결과 두 세트가

SELECT name, count(appearance) as countA from table where results = '1' 
SELECT name, count(appearance) as countB from table where results = '2' 

을 그리고 나는이 같은 측면에서 그들에게 측면을 결합하고 싶었 :

+---------+---------+---------+ 
| col_1 | countA | countB | 
+---------+---------+---------+ 
| John | 3 | 1 | 
| Mary | 1 | 2 | 
| Gary | 2 | NULL | 
| Sean | 4 | NULL | 
| Mike | NULL | 6 | 
+---------+---------+---------+ 

을 어떻게 할 그렇게? 당신은 자기를 사용할 수

답변

4

이 (오라클)을해야 다음과 같이 가입

SELECT name 
    , sum(case results when '1' then 1 else 0 end) as countA 
    , sum(case results when '2' then 1 else 0 end) as countB 
    from table 
where results IN ('1', '2') 
group by 
     name 
+0

그것은 MySql에서도 작동합니다. –

+0

네, 이것이 제가 찾고있는 것입니다. 고마워요^_ ^ – Khairul

-1
SELECT name, count(appearance) as countA, null AS countB from table where results = '1' 
UNION ALL 
SELECT name, null AS countA, count(appearance) as countB from table where results = '2' 
1

은 자기를 필요로하지 않고

select a.col_1, a.countA, b.countB from table a, table b 
where a.col_1 = b.col_1 and a.results='1' and b.results='2' 
+0

영업 이익 모두 나열하고 싶어 가입 'col_1'을 호출하고 일치하는 레코드가없는'count' 컬럼에 NULL을 넣습니다. –

-1
SELECT `table`.name, countA, countB 
FROM tab 
LEFT OUTER JOIN 
    (SELECT name, count(appearance) as countA from `table` where result = '1' group by name) as tmp1 
ON `table`.name = tmp1.name 
LEFT OUTER JOIN 
    (SELECT name, count(appearance) as countB from `table` where result = '2' group by name) as tmp2 
ON `table`.name = tmp2.name; 
관련 문제