Language(R, Python, SQL)/SQL
[SQL] Codility SQL exercise 2번 문제
dtstory
2022. 11. 28. 20:00
https://app.codility.com/programmers/trainings/6/
Exercise 6. SQL - Practice Coding - Codility
Given a list of matches in a group stage of the soccer World Cup, compute the number of points each team currently has.
app.codility.com
Codility SQL exerercise 2번문제 풀이
<문제 출처>
SqlEventsDelta
SqlEventsDelta coding task - Practice Coding - Codility
Compute the difference between the latest and the second latest value for each event type.
app.codility.com
<source code>
select B.event_type, B.value
from (
select A.event_type,
A.value - lead(A.value) over(partition by A.event_type order by A.event_type) as value
from (
select *, rank() over(partition by event_type order by time desc) as ranking
from events
) as A
where A.ranking <= 2
) as B
where B.value is not null
해당 문제 풀이시, 주요 함수 2가지는 lead 와 rank 였다.
풀이의 진행순서는 아래와 같다.
1/ rank 함수를 이용하여, group : event_type , order : time desc 기준으로 ranking 파생변수를 생성한다.
2/ ranking이 2 이하(time sequence 상 상위 2개)인 ranking만 추출
3/ lead 함수를 이용하여, diff value 구하기
4/ null 과의 연산(상위 2번째 값은 lead를 통한 value가 없다.) 결과는 null 이기에, null인 행 제거
728x90