2014-07-10 3 views
0

표 :SQL 체크 여러 행이

id | name | country 
--------------------- 
1 | abc | India 
2 | abc | America 
3 | abc | USA 
4 | xyz | India 
5 | xyz | America 
6 | xyz | USA 

QUERY 지금까지 시도 :

SELECT `id`, 
    if(`country` = 'India',count(id),0) as object1, 
    if(`country` = 'America', count(id),0) as object2, 
    if(`country` = 'USA',count(id),0) as object3 
FROM `table` 

위 같은 나에게 출력을 제공 :

id | name | object1 | object2 | object3 
--------------------------------------------- 
1 | India | 6   | 0  | 0  

다음과 같이 출력하고 싶습니다.

id | name  | object1 | object2 | object3 
--------------------------------------------- 
1 | India  | 1   | 1  | 1  
1 | America | 1   | 1  | 1 
1 | USA  | 1   | 1  | 1 

이 출력물을 얻으려는 사람이 있습니까?

+0

개체 수는 무엇입니까? object1/object2/object3 수와 다른 값의 전체 빈도 간에는 어떤 관계도없는 것 같습니다. GROUP BY와 name, count (*)를 사용할 수 없습니까? – MatsLindh

답변

0

조건부 집계가 필요하다고 생각하지만 개체가 무엇인지 분명하지 않습니다. 데이터를 바탕으로, 나는 생각 :

SELECT country as name, 
     sum(name = 'abc') as abc, 
     sum(name = 'xyz') as xyz 
FROM `table` 
group by country; 
0

이 시도 :

SELECT `id`,`country`, count(`country`) as 'CountOfCountry' 
    FROM `table` 
    GROUP by id,Country 

하는 당신에게 각각의 고유 한 국가의 수, 모든 그룹화를 줄 것이다. "개체"라고 부르는 것이 실제 국가 별 수라고 가정합니다.

0

지원할 견본 데이터가 없기 때문에 세 번째 열이 있어야하는지 잘 모르겠습니다. 그러나 다음 (SQL Fiddle)에 대한 방법 : 당신이 당신의 샘플 출력의 모든 ID를 1만큼 당신의 쿼리 ID를 반환하기를 원한다면

SELECT country, 
    SUM(CASE WHEN name = 'abc' THEN 1 ELSE 0 END) AS object1, 
    SUM(CASE WHEN name = 'xyz' THEN 1 ELSE 0 END) AS object2, 
    SUM(CASE WHEN name = 'nunya' THEN 1 ELSE 0 END) AS object3 
FROM MyTable 
GROUP BY country 
0

나는 확실하지 않았다, 나는 어떻게 확실하지 않다 는 샘플 데이터를 나타내지 만 오타라고 가정합니다. 이것이 내가 생각해내는 것입니다. 당신이 ID를 싶지 않는 다만 국가별로 그룹화 할 일이 다음을 수행하려는 경우 여기에 SQL 바이올린을 지금 http://sqlfiddle.com/#!6/b763d/7

select id,country, 
(select count(id) from things where country='india') as object1, 
(select count(id) from things where country='america') as object2, 
(select count(id) from things where country='usa') as object3 
from things 

입니다.

select country, 
(select count(id) from things where country='india') as object1, 
(select count(id) from things where country='america') as object2, 
(select count(id) from things where country='usa') as object3 
from things 
group by country