Weather Observation Station 5
Problem
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:
(STATION 테이블에서 가장 짧고, 가장 긴 CITY 이름과 그에 해당하는 이름 길이(즉, 이름에 있는 문자 수)를 조회하시오. 만약 가장 작거나 큰 도시가 여러 개인 경우, 알파벳 순으로 가장 먼저 오는 도시를 선택하시오.)
Sample Input
For example, CITY has four entries: DEF, ABC, PQRS and WXY.
(예를 들어, CITY에는 네 개의 항목이 있다: DEF, ABC, PQRS, 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 options for shortest named city. Choose ABC, because it comes first alphabetically.
(알파벳 순으로 정렬했을 때, CITY 이름은 ABC, DEF, PQRS, WXY로 나열되며, 이름의 길이는 각각 3, 3, 4, 3이다. 가장 긴 이름은 PQRS이지만, 가장 짧은 이름을 가진 도시에는 여러 옵션이 있다. 알파벳 순으로 가장 먼저 오는 ABC를 선택해야 한다.)
Note
You can write two separate queries to get the desired output. It need not be a single query.
(두 개의 분리된 쿼리로 작성할 수 있다.)
Solution(Oracle)
-- 가장 짧은 CITY 이름과 그 길이를 찾는 쿼리
SELECT CITY, LENGTH(CITY)
FROM (
SELECT CITY
FROM STATION
ORDER BY LENGTH(CITY), CITY
)
WHERE ROWNUM = 1;
-- 가장 긴 CITY 이름과 그 길이를 찾는 쿼리
SELECT CITY, LENGTH(CITY)
FROM (
SELECT CITY
FROM STATION
ORDER BY LENGTH(CITY) DESC, CITY ASC
)
WHERE ROWNUM = 1;
FROM절에 사용하는 서브쿼리
- Oracle SQL에서 FROM 절에 사용하는 서브쿼리는 "인라인 뷰" 또는 "내부 쿼리"라고 한다.
LENGTH 함수- 문자열의 길이 측정
- 주어진 문자열의 길이를 측정해, 그 결과를 숫자로 반환한다.
ROWNUM - 순서대로 번호 매기기
- Oracle 데이터베이스의 ROWNUM 기능은 조회된 결과의 각 행에 순차적으로 번호를 부여한다. 번호는 조회되는 순서에 따라 1부터 자동으로 할당된다. (특히, 결과 집합에서 상위 N개의 데이터만 선택하고 싶을 때 유용하다.)
- ROWNUM을 사용할 때 정렬을 원하면, 서브쿼리 내에서 먼저 ORDER BY로 정렬한 후, 외부 쿼리에서 ROWNUM을 적용해야 원하는 순서대로 데이터를 추출할 수 있다.
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
이 포스팅은 개인 학습 목적으로 작성되었습니다.
번역이나 코드가 정확하지 않을 수 있습니다.
'SQL' 카테고리의 다른 글
[HackerRank SQL] Weather Observation Station 7 (Oracle) (0) | 2024.03.31 |
---|---|
[HackerRank SQL] Weather Observation Station 6 (Oracle) (0) | 2024.03.30 |
[HackerRank SQL] Weather Observation Station 4 (Oracle) (0) | 2024.03.28 |
[HackerRank SQL] Weather Observation Station 3 (Oracle) (0) | 2024.03.27 |
[HackerRank SQL] Weather Observation Station 1 (Oracle) (0) | 2024.03.26 |