본문 바로가기
서버/MYSQL

[MYSQL] HACKERRANK - Weather Observation Station 5

by HDobby 2022. 6. 6.

https://www.hackerrank.com/challenges/weather-observation-station-5/problem

 

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

문제

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.

Sample Input

For example, CITY has four entries: DEF, ABC, PQRS and WXY.

Sample Output

ABC 3
PQRS 4

Explanation

When ordered alphabetically, the CITY names are listed as ABC, DEF, PQRS, and WXY, with lengths 3, 3, 4 and 3. The longest name is PQRS, but there are 3 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.

생각해보기

CITY의 길이가 가장 짧은 것과 긴 것 출력

길이가 같으면 CITY의 알파벳 순 중 맨 앞에 오는 것 출력

2가지의 쿼리를 사용해도 가능

 

코드

더보기

길이가 가장 짧은 것 하나 출력

SELECT CITY
FROM STATION
ORDER BY LENGTH(CITY) ASC, CITY
LIMIT 1

길이가 가장 긴 것 하나 출력

SELECT CITY
FROM STATION
ORDER BY LENGTH(CITY) DESC, CITY
LIMIT 1

 

전체

SELECT CITY, LENGTH(CITY)
FROM STATION
WHERE CITY = (
        SELECT CITY
        FROM STATION
        ORDER BY LENGTH(CITY) ASC, CITY
        LIMIT 1
    ) OR
    CITY = (
        SELECT CITY
        FROM STATION
        ORDER BY LENGTH(CITY) DESC, CITY
        LIMIT 1
    )
ORDER BY LENGTH(CITY)
728x90

댓글