STATION의 두 도시에 각각의 길이(예: 이름의 문자 수)와 함께 가장 짧은 도시와 긴 도시 이름을 조회하라. (단, 가장 작거나 큰 도시가 둘 이상 있는 경우 알파벳 순서로 정렬할 때, 가장 먼저 오는 도시를 선택하시오.)
with rank_cte as (
select city, rank() over(order by length(city) desc) as rank_number
from station
order by rank_number, city
)
select city, length(city)
from rank_cte
where rank_number = (select min(rank_number) from rank_cte) or
rank_number = (select max(rank_number) from rank_cte)
limit 2
- CTE에서 Window function을 사용, 도시 이름과 도시 길이 순위 table 제작
- 순위, 도시 순으로 정렬
- 메인 쿼리 where 절에서 서브 쿼리를 활용, 순위가 가장 높거나 낮은 경우 추출
- order by로 알파벳 정렬되었기 때문에, limit 구문 사용
해당 문제에서는 min(rank)의 경우가 1가지여서 위의 방식으로 문제를 풀 수 있지만, 좋은 방법은 아니라고 생각한다. 또한, 쿼리가 불필요하게 복잡하다.
(select city, length(city) from station order by length(city) limit 1)
union
(select city, length(city) from station order by length(city) desc limit 1)
Union을 활용한 쿼리를 사용하면 보다 빠르고, 직관적으로 결과를 추출할 수 있다. 데이터가 클수록 SQL의 효율성 또한 중요하기 때문에, 복잡한 방법보다는 단순하면서 빠른 쿼리가 실무에서 유용하게 사용된다.
Weather Observation Station 5 | HackerRank
Write a query to print the shortest and longest length city name along with the length of the city names.
www.hackerrank.com
'코딩 테스트 > SQL' 카테고리의 다른 글
| [MySQL] 프로그래머스 - 특정 조건을 만족하는 물고기별 수와 최대 길이 구하기 (0) | 2024.06.25 |
|---|---|
| [MySQL] - Placements (0) | 2024.02.08 |
| [MySQL] HackerRank - Weather Observation Station 20 (2) | 2024.01.16 |
| [MySQL] HackerRank - The PADS (0) | 2024.01.16 |
| [MySQL] HackerRank - The Report (2) | 2024.01.14 |