코딩 연습/SQL
[HackerRank] 가장 길고 짧은 City 고르기
썬2
2021. 4. 2. 16:08
Weather Obsrvation Station5
Query the two cities in STATION with the shortest and longest CITY names, as well as their respective lengths (i.e.: number of characters in the name). If there is more than one smallest or largest city, choose the one that comes first when ordered alphabetically.
The STATION table is described as follows:
(생략)
나의 코드:
# 이름이 제일 긴 city 테이블
with max_city (city, value) as
(select city, length(city) as ln
from station
order by length(city) desc, city
limit 1),
min_city (city, value) as # 이름이 제일 짧은 city 테이블
(select city, length(city) as ln
from station
order by length(city), city
limit 1)
select * from min_city
union # union으로 두 값 row로 합치기
select * from max_city;
포인트:
1. length함수를 이용하여 단어의 개수를 센다.
2. order by 와 limit으로 제일 짧고 긴 것을 고른다.
3. 한 쿼리로 작성하기 위해 with 구문으로 두개의 테이블을 만들고 union으로 합친다.
다른 코드:
with 구문 없이 그냥 위에 union으로 합쳤다.
느낀점:
문제에는 두 쿼리로 써도 된다고 했는데 오기가 생겨 한 쿼리로 작성해보았다.
min()함수를 쓰고 싶었는데 안되더라. 구글링해도 mysql로 한 사람들은 다 이런식으로 풀었는데 왜 안되는지 모르겠다ㅠㅜ 모르면 물어보자!