몸과 마음이 건전한 SW 개발자

[HackerRank-MSSQL] 해커랭크 basic select Weather Observation Station 5 [다시 풀어 보기] 본문

SQL/MSSQL

[HackerRank-MSSQL] 해커랭크 basic select Weather Observation Station 5 [다시 풀어 보기]

스위태니 2026. 4. 17. 11:17
728x90

문제 링크

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

 

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

 

정답 코드

SET NOCOUNT ON;

SELECT TOP 1 CITY, LEN(CITY)
FROM STATION
ORDER BY LEN(CITY) ASC, CITY ASC;

SELECT TOP 1 CITY, LEN(CITY)
FROM STATION
ORDER BY LEN(CITY) DESC, CITY ASC;

go

틀린 코드

SET NOCOUNT ON;

select city, len(city) from station where len(city) = max(len(city)) or len(city) = min(len(city));
/*
Enter your query here.
Please append a semicolon ";" at the end of the query and enter your query in a single line to avoid error.
*/

go

풀이 과정

  1. 각각 하나씩 출력한다.
  2. 도시 이름 길이가 긴 순, 짧은 순으로 정렬한다.
    1. 긴 순일 경우 내림차순
    2. 짧은 순일 경우 오름차순
  3. 정렬한 select의 가장 위에 행을 출력하면 끝

느낀점

  • 두 번 나눠서 출력하면 된다.
  • my sql에서 limit만 생각했는데 여기는 top으로 하면 해결된다.
  • bottom은 없어서 정렬 후 맨 위만 뽑아야 한다.
  • top 1도 있으니 top 2 ... n이 가능하다.
728x90