Language(R, Python, SQL)/SQL

[SQL] HackerRank - SQL Problem <easy>

dtstory 2022. 12. 8. 22:00

HackerRank 라는 사이트에 SQL 쿼리 연습을 위한 있는 문제들이 있었다.

https://www.hackerrank.com/domains/sql

 

Solve SQL Code Challenges

A special-purpose language designed for managing data held in a relational database.

www.hackerrank.com

문제 풀이시, 헷갈렸거나 암기가 필요하다고 느꼈던 함수들 위주로 풀이방법을 게재하고자 한다. (MySQL)

 

 

SelectWeather Observation Station5 (length)

 

도시 명이 가장 짧거나 긴 row 를 필터링하는 문제다.

여기서 사용되는 주요 함수는 length() 인데, 이 때, limit 1을 적절히 사용하여 OR로 연결해주는 것이 핵심이다. 

 

select city, length(city)
from station
where id = (
    select id
    from station
    order by length(city), city
    limit 1
)
or id = (
    select id
    from station
    order by length(city) desc, city
    limit 1
)

 

 

 

SelectWeather Observation Station 6 ~ 12 (like, left, right)

 

city의 첫 글자가 모음으로 시작하는 String만을 추출하는 쿼리를 만들어보자. 2가지 방법으로 접근할 수 있는데, 1번보다는 2번의 방법으로 접근하는 것이 좋겠다.

 

1. OR을 이용한 연결

select distinct(city)
from station
where city like 'I%'
    or city like 'E%'
    or city like 'U%' 
    or city like 'A%' 
    or city like 'O%'

 

2. left() 함수를 이용한 방법

   - left(변수명, 시프트횟수): 첫 문자부터 시프트횟수까지의 string을 추출하는 함수

select distinct(city)
from station
where left(city,1) in ('I','E','A','U','O')

 

유사한 방식으로 Weather Observation Station 7 ~ 12까지는 무난하게 해결할 수 있을 것이다.

 

 

 

SelectWeather Observation Station 20 (percent_rank)

 

Oracle SQL에서 사용가능한 median 함수가 없기에 percent_rank 함수를 이용해서 쿼리할 수 있다.

select round(lat_n,4)
from (
    select lat_n, percent_rank() over(order by lat_n) lat_rank
    from station
) A
where A.lat_rank = 0.5

 

 

 

Aggregation > The Blunder (ceil, replace, convert)

 

1. salary(integer 형) 을 salary(char 형) 으로 변환(convert)해준다.

2. replace 함수를 이용해서 '0' 인 문자를 '' 공백으로 치환한다

3. 연산된 값에 ceil 함수를 사용하여 올림 처리를 한다.

※ 참고 ※
ceil : 올림
round : 반올림
floor : 버림
truncate : 내림 
abs : 절대값
mod(x,y) : x를 y로 나눈 나머지

 

select ceil(avg(salary) - avg(replace(convert(salary, char),'0','')))
from employees

 

사실 아래 코드와 같이, integer 형의 경우 convert 함수를 이용한 char형으로의 치환없이도 코드는 동작한다.

select ceil(avg(salary) - avg(replace(salary,'0','')))
from employees

 

 

Basic Join > The Report(between, if)

 

1. inner join 을 이용해 students 테이블과 grades 테이블을 조인한다.

2. 조인 조건으로 일치가 아닌 범위를 설정할 수 있다. (between A and B 를 이용) 

3. if(조건, 참일 경우 반환값, 거짓일 경우 반환값) 조건을 이용해, grade가 8 미만인 경우 이름을 NULL 로 치환한다.

select if(g.grade > 7, s.name, NULL), g.grade, s.marks
from students s
inner join grades g
on s.marks between g.min_mark and g.max_mark
order by g.grade desc, s.name, s.marks

 

 

Alternative Queries > Draw The Triangle 2

 

1. set 을 이용한 초기값 할당 ->  0

2. repeat(반복할value , 반복할 횟수) -> "* " 문자를 1번 ,2번 ,3번 .. ,20번 반복

set @number = 0;

select repeat("* ", @number := @number + 1)
from information_schema.tables
limit 20

 

 

 

 

Advanced Select > Type of Triangle

삼각형의 종류를 조건에 맞게 출력하는 문제인데, Not A Triangle 조건에 <= (이상) 을 쓰지 않고, <(초과) 를 써버리게 되면 오답처리가 된다. 삼각형이 아닌 선 이 만들어지기 때문이다. 너무나도 당연한 생각인데, 조건에만 포커싱하다보니, 이러한 점을 놓치게 된 것 같다.

select case
        when (A + B <= C) or (A + C <= B) or (B + C <= A) then "Not A Triangle"
        when (A = B and B = C) then "Equilateral"
        when (A != B and B != C and A != C)  then "Scalene"
        else "Isosceles"
       end 
from TRIANGLES

 

 


 

이번 게시글에서는 Hacker Rank SQL 문제<easy> 중 한 번이라도 막혔거나 암기하여야 할 함수가 있는 문제들을 추려서 solution을 게재해 보았다. 오랜만에 문제를 풀어보니까 재밌고 도움이 많이 되었다!

 

다음 포스팅엔 medium 문제 풀이를 올릴 예정이다. 

728x90