2024. 1. 6. 17:25ㆍCoding/LeetCode-SQL
문제 링크
Average Time of Process per Machine - LeetCode
Can you solve this real interview question? Average Time of Process per Machine - Table: Activity +----------------+---------+ | Column Name | Type | +----------------+---------+ | machine_id | int | | process_id | int | | activity_type | enum | | timestam
leetcode.com
문제
코드
# Write your MySQL query statement below
SELECT start.machine_id, ROUND(AVG(end.timestamp - start.timestamp), 3) AS processing_time
FROM Activity start
JOIN Activity end
ON end.machine_id = start.machine_id
WHERE start.activity_type = 'start' AND end.activity_type = 'end'
GROUP BY start.machine_id;
1. 한 테이블에 대해서 INNER JOIN 을 시행해준다.
Activity 테이블의 기본 키는 machine_id, process_id, activity_type으로 세 개이지만 조인하는 칼럼은 machine_id로 지정해준다. ('The resulting table should have the machine_id along with the average time as processing_time, -결과 테이블에는 processing_time으로 표시된 평균 시간에 따른 machine_id가 필수적으로 있어야만 한다. 라는 조건 때문이다.)
그리고 같은 조건으로 인해 GROUP BY절에 machine_id를 넣어준다.
2. 'rounded to 3 decimal places' (소수점 3자리에서 반올림하라) -> ROUND() 함수 사용, 이때 ROUND(, 3)이 된다.
3. WHERE 절에 start인 경우의 activity_type과 end인 경우의 activity_type을 추리기 위해 위와 같은 코드를 작성해준다.
4. end 상태의 timestamp와 start 상태의 timestamp의 평균을 구하라 했으므로 AVG()함수 안에 우선 두 timestamp의 차이를 넣는다.
그리고 이 AVG() 함수를 ROUND 함수의 첫째 항에 넣는다.
'Coding > LeetCode-SQL' 카테고리의 다른 글
[LeetCode] SQL 50 / MySQL / 1280. Students and Examinations (0) | 2024.01.06 |
---|---|
[LeetCode] SQL 50 / MySQL / 577. Employee Bonus (0) | 2024.01.06 |
[LeetCode] SQL 50 / MySQL / 197. Rising Temperature (1) | 2024.01.06 |
[LeetCode] SQL 50 / ORACLE / 1581. Customer Who Visited But Did Not Make Any Transactions (0) | 2024.01.06 |
[LeetCode] SQL 50 / ORACLE / 1068. Product Sales Analysis 1 (1) | 2024.01.06 |