/////
Search
Duplicate

Weather Observation Station 5

태그
Select
ORDER BY
한 번 더 체크

문제

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 STATIONtable is described as follows:
where LAT_N is the northern latitude and LONG_W is the western longitude.

예제

For example, CITY has four entries: DEF, ABC, PQRS and WXY.
Sample Output
ABC 3 PQRS 4
SQL
복사

정답

SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY), CITY LIMIT 1; SELECT CITY, LENGTH(CITY) FROM STATION ORDER BY LENGTH(CITY) DESC, CITY LIMIT 1;
SQL
복사

풀이

문자형 데이터의 길이를 재는 함수는 LENGTH()이다.
LENGTH(CITY)
SQL
복사
문제에서 주어진 정렬 조건은 두 개이다. (1) 도시 문자열의 길이 (2) 알파벳 순서
따라서 ORDER BY 절에 순서대로 LENGTH(CITY)와 CITY를 넣는다. 다만, 가장 짧은 도시를 구하려면 오름차순으로, 긴 도시를 구하려면 내림차순으로 구해야 한다.
ORDER BY LENGTH(CITY), CITY ORDER BY LENGTH(CITY) DESC, CITY
SQL
복사
마지막으로 “가장” 긴 것과 “가장” 짧은 것이므로 LIMIT을 통해 한 개만 출력한다.
LIMIT 1
SQL
복사