https://www.hackerrank.com/challenges/weather-observation-station-18/problem?isFullScreen=true
Weather Observation Station 18 | HackerRank
Query the Manhattan Distance between two points, round or truncate to 4 decimal digits.
www.hackerrank.com
Consider and to be two points on a 2D plane.
- happens to equal the minimum value in Northern Latitude (LAT_N in STATION).
- happens to equal the minimum value in Western Longitude (LONG_W in STATION).
- happens to equal the maximum value in Northern Latitude (LAT_N in STATION).
- happens to equal the maximum value in Western Longitude (LONG_W in STATION).
Query the Manhattan Distance between points and and round it to a scale of decimal places.
Input Format
The STATION table is described as follows:

위 문제는 경위도의 최솟값 좌표와 최대값 좌표의 맨하튼 거리를 구하는 문제이다. 좌표 (a,b), (c,d) 가 주어져 있다면 맨하튼 거리를 구하는 공식은 다음과 같다.
|a-c| +|b-d|
절댓값을 SQL로 구현하기 위한 함수는 ABS이다. 따라서 맨하튼 거리를 구하는 코드는 아래와 같다.
SELECT ROUND(ABS((MIN(LAT_N) - MAX(LAT_N))) + ABS((MIN(LONG_W) - MAX(LONG_W))),4)
FROM STATION
https://www.hackerrank.com/challenges/weather-observation-station-19/problem?isFullScreen=true
Weather Observation Station 19 | HackerRank
Query the Euclidean Distance between two points and round to 4 decimal digits.
www.hackerrank.com
이 문제는 위 문제에서 유클리드 거리를 구하는 문제이다. 유클리드 거리를 구하는 공식은 다음과 같다.
루트와 제곱을 이용해야 하는데 이를 SQL에 구현하기 위해서는 SQRT와 POWER를 사용하면 된다.
SQRT는 입력 숫자의 제곱근을 구하는 것이고, POWER는 입력 숫자의 거듭제곱을 구하는 것이다.
따라서 정답 코드는 다음과 같다.
SELECT ROUND(SQRT(POWER(MIN(LAT_N)-MAX(LAT_N),2)+POWER(MIN(LONG_W)-MAX(LONG_W),2)),4)
FROM STATION
POWER는 (입력 숫자, 거듭제곱 횟수)로 사용할 수 있다. 위 문제는 거듭제곱을 이용하기 때문에 거듭제곱 횟수를 2로 둔 것이다.
SQRT는 숫자의 제곱근만을 구해주는 함수이다. 세제곱근을 구해주는 CBRT라는 함수도 있지만 그 이상의 제곱근을 구해주는 함수는 없는 것 같다.
'SQL' 카테고리의 다른 글
JOIN이 포함된 서브쿼리 (0) | 2023.01.13 |
---|---|
공통행이 없는 두 테이블의 JOIN (0) | 2023.01.12 |
SQL) CONCAT (0) | 2023.01.10 |
정규표현식 REGEXP (0) | 2023.01.09 |
상품을 구매한 회원 비율 구하기 (0) | 2023.01.09 |