2014-11-10 7 views
0

저는 아티스트와 아트 워크라는 두 개의 테이블을 가지고 있습니다. 아래는 artist.name = artwork.artist의 INNER JOIN입니다.두 테이블에없는 행을 삭제하지 않고 테이블을 조인하는 방법은 무엇입니까?

남성보다 여성이 더 많이 만든 도시를 나열해야합니다.

select location, count(gender) from 
(artist inner join artwork on name = artist) 
where gender="male" group by location; 

enter image description here

그런 다음 나는 동일한 기능을 수행하지만, 여성 아티스트 얻을 :

enter image description here

먼저 나는 얼마나 많은 남성 각 도시에 의해 만들어진 작품 찾을 수 있습니다.

select location, count(gender) from 
(artist inner join artwork on name = artist) 
where gender="female" group by location; 

여기에서 나는 어디로 가나 요? 왼쪽 테이블을 조인하고 남성> 여성이있는 도시를 선택했습니다. 이처럼

: 내가 얻을

select city_male from ( 

    (select location as city_male, count(gender) as male_art from (artist inner join artwork on name = artist) 
    where gender="male" group by location) 

    LEFT JOIN 

    (select location as city_female, count(gender) as female_art from (artist inner join artwork on name = artist) 
    where gender="female" group by location) 

    on city_female = city_male 

) 
where male_art > female_art 
; 

결과는 내가 필요로하는 일에 가까운,하지만 한 남녀의 작품을 포함하는 도시가 가입 후 손실됩니다.

어떻게이 테이블을 하나로 통합하고 여성보다 남성이 더 많은 작품을 가진 도시를 선택합니까?

답변

1
on 절에 where 절을 이동

: 일치가없는

on city_female = city_male and male_art > female_art 

경우에도 도시를 얻을 수 있습니다.

select location as city_male, 
     sum(case when gender = 'male' then 1 else 0 end) as male_art, 
     sum(case when gender = 'female' then 1 else 0 end) as female_art 
from artist inner join 
    artwork 
    on name = artist) 
group by location 
having sum(case when gender = 'male' then 1 else 0 end) > sum(case when gender = 'female' then 1 else 0 end); 
:

나는 쿼리가 group byhaving를 사용하여 쓰기 쉬울 것이라고 생각

관련 문제