[LeetCode] Average Time of Process per Machine

아르당·2026년 6월 9일

LeetCode

목록 보기
350/561
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

Table: Activity

column NameType
machine_idint
process_idint
activity_typeenum
timestampfloat

이 표는 공장 웹사이트에 대해 사용자 활동을 보여준다.
(machine_id, process_id, activity_type)은 이 테이블의 기본 키이다.
machine_id는 기계 ID이다.
process_id는 machine_id를 가진 머신에서 실행 중인 프로세스 ID이다.
activity_type은 type('start', 'end')의 ENUM(category)이다.
timestamp는 현재 시간을 초 단위로 나타내는 실수이다.
'start'는 기계가 해당 시간에 작업을 시작함을 의미하고, 'end'는 기계가 해당 시간에 작업을 종료함을 의미한다.
따라서 모든 (machine_id, process_id)는 'start'와 'end'가 존재함을 보장한다.

여러 대의 기계가 각각 동일한 수의 프로세스를 실행하는 공장 웹사이트가 있다. 각 기계가 프로세스를 완료하는데 걸리는 평균 시간을 구하는 방법을 작성해라.

작업 완료 시간은 'end'에서 'start'를 뺀 값이다. 평균 시간은 해당 기계에서 모든 작업의 완료 시간을 합한 후 실행된 작업 수로 나눈 값이다.

결과는 machine_id와 processing_time의 평균 시간이 포함되어야 하고, 평균 시간은 소수점 셋째 자리에서 반올림한다.

결과는 순서와 관계없이 반환한다.

Example

Input:
Activity table:

machine_idprocess_idactivity_typetimestamp
00start0.712
00end1.520
01start3.140
01end4.120
10start0.550
10end1.550
11start0.430
11end1.420
20start4.100
20end4.512
21start2.500
21end5.000

Output:

machine_idprocessing_time
00.894
10.995
21.456

Explanation:
기계 3대에 각각 2개 작업이 실행했다.
기계 0의 평균 시간은 ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894이다.
기계 1의 평균 시간은 ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995이다.
기계 2의 평균 시간은 ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456이다.

Solved

-- Write your PostgreSQL query statement below
select A.machine_id, round(avg(B.timestamp - A.timestamp):: numeric, 3) as processing_time
from Activity A
join Activity B
on A.machine_id = B.machine_id
and A.process_id = B.process_id
and A.activity_type = 'start'
and B.activity_type = 'end'
group by A.machine_id;
profile
내 마음대로 코드 작성하는 세상

0개의 댓글