IT/SQL

[해커랭크] Weather Observation Station 5

김보통김보름 2023. 3. 18. 09:45
728x90
반응형

문제링크 : https://www.hackerrank.com/challenges/weather-observation-station-5/problem?isFullScreen=true

 

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 InputFor example, CITY has four entries: DEF, ABC, PQRS and WXY.


Sample Output
ABC 3
PQRS 4


ExplanationWhen 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
NoteYou can write two separate queries to get the desired output. It need not be a single query.

SELECT CITY, LEN
  FROM (
        SELECT CITY,
        LENGTH(CITY) LEN,
        ROW_NUMBER() OVER(ORDER BY LENGTH(CITY), CITY) as RN_MIN,
        ROW_NUMBER() OVER(ORDER BY LENGTH(CITY) DESC, CITY) as RN_MAX
        FROM STATION
       )
 WHERE (RN_MIN = 1 OR RN_MAX = 1)
 ORDER BY LEN;

OVER()

  • ORDER BY, GROUP BY 서브쿼리를 개선하기 위해 나온 함수
  • 쿼리를 짧게 만들어준다.
 
728x90