Average Time of Process per Machine

수이·2025년 4월 17일

🟢 코드카타 / SQL

목록 보기
86/88

There is a factory website that has several machines each running the same number of processes.
Write a solution to find the average time each machine takes to complete a process.
The time to complete a process is the 'end' timestamp minus the 'start' timestamp. The average time is calculated by the total time to complete every process on the machine divided by the number of processes that were run.
The resulting table should have the machine_id along with the average time as processing_time, which should be rounded to 3 decimal places.
문제링크

조건정리

  1. 공정 완료하는 데 걸리는 평균 시간 구하기
  • 프로세스 완료 시간
    (end timestamp) - (start timestamp)
  • 평균 시간
    프로세스 완료 총 시간 / 실행된 총 프로세스 수
  1. machine_id, processing_time 출력
    • 소수점 셋째 자리로 반올림

풀이

WITH act_start AS
(
    SELECT machine_id, process_id, timestamp AS start_time
    FROM activity 
    WHERE activity_type = 'start'
),
act_end AS
(
    SELECT machine_id, process_id, timestamp AS end_time
    FROM activity
    WHERE activity_type = 'end'
)

SELECT s.machine_id,
       ROUND(AVG(e.end_time - s.start_time), 3) AS processing_time 
FROM act_start s 
INNER JOIN act_end e 
ON s.machine_id = e.machine_id
   AND s.process_id = e.process_id 
GROUP BY s.machine_id

다른사람 풀이

SELECT 
    A.machine_id, 
    ROUND(AVG(B.timestamp - A.timestamp), 3) AS processing_time
FROM 
    Activity A
    INNER JOIN Activity B ON B.machine_id = A.machine_id
                          AND B.process_id = A.process_id
WHERE 
    A.activity_type = 'start'
    AND B.activity_type = 'end'
GROUP BY 
    A.machine_id;

엥 ㅋㅋ 뭔가 내 거보다 간단해 보임
근데 실행 결과 보면 근소하게 내 거가 더 빠르다
이유가 머지..?

무튼 이게 쓰기에는 더 효율적이여 보이긴 함

0개의 댓글