SQL

HackerRank SQL 3문제 풀이 (3)

얆생 2025. 2. 4. 01:19

1. Weather Observation Station 3

 

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

 

Weather Observation Station 3 | HackerRank

Query a list of unique CITY names with even ID numbers.

www.hackerrank.com

/*
짝수인 id number를 가지는 시티 네임, 중복 제외
짝수는 2로 나눠지는거
*/
SELECt DISTINCT city
FROM station
WHERE id % 2 = 0

 

↓ where절에 이렇게도 쓸 수 있음

SELECt DISTINCT city
FROM station
WHERE MOD(id, 2) = 0

 

 

2. Weather Observation Station 19

 

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

/*
p1과 p2의 유클리디안 거리 구하기, 소수점 4자리까지 반올림 round
a,b는 lat_n의 최소, 최대값이고 c,d는 long_w의 최소, 최대값
d(p,q)= sqrt{(a-b)^+(c-d)^}
*/
SELECT ROUND(
       SQRT(
       POWER(MIN(lat_n) - MAX(lat_n), 2) + POWER(MIN(long_w) - MAX(long_w), 2)), 4)
FROM station

 

 

수식이 복잡한걸 만났을 때, select문에 a, b, c, d를 AS로 먼저 지정해보고

최종 연산식에 복붙 대입만 해주면 조금 더 편하다!

 

 

3. Placements

 

https://www.hackerrank.com/challenges/placements/problem?isFullScreen=true

 

Placements | HackerRank

Write a query to output the names of those students whose best friends got offered a higher salary than them.

www.hackerrank.com

 

문제 접근


- 스튜던트 중에 자기보다 높은 월급 받는 베스트프렌드 이름을 추출, 중복되는 숫자의 월급은 없음
- join인데 friend_id에 맞는 salary가 같이 나타나게끔..

- 정렬은 salary 금액 기준 오름차순(내림차순이라는 언급이 없었으므로 디폴트는 asc)

 

>>결국 못풀어서 해설 참고..
     self join 활용, 테이블이 연결되는 구조를 잘 이해해야 할 것 같음

 

>> friend가 버는 월급을 packages 테이블에서 갖다 매칭시키고 싶으면, 조인을 따로 한번 더 해야됌

>> 내가 버는 월급 표시할 때는 p1으로 조인, 친구 월급 매칭은 p2로 조인

 

최종 코드

SELECT s.name
FROM students s
     INNER JOIN friends f ON s.id = f.id
     INNER JOIN packages p1 ON s.id = p1.id
     INNER JOIN packages p2 ON f.friend_id = p2.id
WHERE p1.salary < p2.salary
ORDER BY p2.salary