cs

Codility라는 곳에서도 sql 문제를 면접볼때 많이 내는 것을 알았다. 한국기업도 미국기업에서도 자주 사용한다고 하는데, 문제가 많이 없어서 좀 아쉬웠지만 다른 곳에 비해서 연습문제의 난이도가 살짝 높은? 자주쓰는 쿼리를 묻는 문제가 나오는 것 같다. 


Easy Level - Compute the difference between the latest and the second latest value for each event type.

 

Given a table events with the following structure: create table events ( event_type integer not null, value integer not null, time timestamp not null, unique(event_type, time) );

 

write an SQL query that, for each event_type that has been registered more than once, returns the difference between the latest (i.e. the most recent in terms of time) and the second latest value. The table should be ordered by event_type (in ascending order).

 

For example, given the following data:

your query should return the following rowset:

For the event_type 2, the latest value is 2 and the second latest value is 7, so the difference between them is −5.

The names of the columns in the rowset don't matter, but their order does.


나름 생각을 해야하는 문제.. 

[My Answer]

SELECT 
A.event_type AS event_type, 
A.value - B.value AS value 
FROM
(SELECT
    event_type,
    value,
    rank() over(partition by event_type order by time desc) rank
FROM events) A,
(SELECT
    event_type,
    value,
    rank() over(partition by event_type order by time desc) rank
FROM events) B
WHERE A.event_type = B.event_type
AND A.rank = 1
AND B.rank = 2

두개 테이블 합쳐주고 그 안에서 이벤트 시간에 랭크를 줬다. 

다른 블로그도 보면 이런 방식으로 다 사용 하는데, 이것 말고 뭔가 그냥 시간에서 subtract를 하는 사람도 있던데.. 어떤게 편한지는 쿼리 날리는 사람 나름인듯.. 

 

 

'Code Problems > SQL_Codility' 카테고리의 다른 글

[Codility] - SqlWorldCup  (0) 2021.09.29

+ Recent posts