SQL/StrataScratch
[MySQL] (Medium) Number Of Units Per Nationality
oatmeal
2024. 2. 14. 11:35
문제: https://platform.stratascratch.com/coding/10156-number-of-units-per-nationality?code_type=3
나의풀이:
select nationality
, count(*) as apartment_count
from airbnb_hosts h
join airbnb_units u using (host_id)
where age < 30
and unit_type = 'Apartment'
group by nationality
order by 2 desc;
틀림!!! 왜??'
솔루션:
SELECT
nationality,
count(distinct unit_id) as apartment_count
FROM airbnb_units apartment
INNER JOIN airbnb_hosts host
ON apartment.host_id = host.host_id
WHERE host.age < 30
AND unit_type = 'Apartment'
GROUP BY host.nationality
ORDER BY apartment_count DESC
카운트(*)가 아니라 카운트(distinct unit_id) 였다
왜..?
데이터를 살펴보니 host 테이블에 중복값이 존재한다. 왜..? 왜 그렇게 해뒀을까
그리고 units 테이블에는 중복값이 없다
그래서 두 테이블을 이너 조인하면 중복행이 존재하게 되어서
카운트 할 때 디스팅트 유닛을 해줘야한다
디스팅트 호스트 가 아닌이유는 한 호스트가 여러 유닛을 소유할 수 있기 때문에 유니크한 유닛 값을 세는 듯
문제만 보고 냅다 쿼리 짜지 말고 데이터를 잘 살피자 ㅋㅅㅋ