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:

where LAT_N is the northern latitude and LONG_W is the western longitude.
Explanation
When ordered alphabetically, the CITY names are listed as ABC, DEF, PQRS,and WXY, with lengths and . The longest name is PQRS, but there are options for shortest named city. Choose ABC, because it comes first alphabetically.
Note
You can write two separate queries to get the desired output. It need not be a single query.
STATION 테이블에서 도시 이름(CITY)의 길이가 가장 짧은 도시와 가장 긴 도시를 구하세요. 각각의 이름과 그 길이도 함께 출력하세요. 같은 길이일 경우, 알파벳 순으로 가장 먼저 오는 도시를 선택하세요.
(
select city, length(city) as len
from station
order by len asc, city asc
limit 1
)
union
(
select city, length(city) as len
from station
order by len desc, city asc
limit 1
);
- 첫 번째 쿼리는 도시 이름의 길이(LENGTH) 를 기준으로 오름차순 정렬하고 (LEN ASC),
- 길이가 같다면 알파벳 순으로 정렬하기 위해 CITY ASC를 추가합니다.
- LIMIT 1로 가장 짧고 알파벳 순으로 가장 앞선 도시 하나만 선택합니다.
- 두 번째 쿼리는 위와 동일한 방식이지만, LEN DESC로 길이가 긴 순서대로 정렬합니다.
- 마찬가지로 CITY ASC를 추가하여 동일 길이일 경우 가장 앞선 도시를 선택합니다.
- UNION을 사용해 짧은 도시와 긴 도시를 한 테이블에 결합합니다.
- UNION은 중복을 제거하지만, 이 경우에는 두 결과가 확실히 다르므로 문제 없음.
'Computer Science > SQL' 카테고리의 다른 글
SQL | HackerRank 문자열을 이어붙이기 (CONCAT) (0) | 2025.06.14 |
---|---|
SQL | HackerRank 정규표현식으로 도시 찾기 – DISTINCT와 REGEXP 활용 (0) | 2025.06.13 |
SQL | HackerRank 삼각형 분류하기: 조건문 CASE를 활용한 다중 조건 처리 (0) | 2025.06.11 |
SQL | LeetCode 1327. 특정 월 기준 주문량 분석하기 (0) | 2025.06.10 |
SQL | LeetCode 1484. 날짜별로 팔린 제품들 정리하기 (GROUP BY + 정렬 + 문자열 조합) (3) | 2025.06.09 |