문제
Average Time of Process per Machine - LeetCode
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.
Return the result table in any order.
The result format is in the following example.
Example 1:
Input:
Activity table:
+------------+------------+---------------+-----------+
| machine_id | process_id | activity_type | timestamp |
+------------+------------+---------------+-----------+
| 0 | 0 | start | 0.712 |
| 0 | 0 | end | 1.520 |
| 0 | 1 | start | 3.140 |
| 0 | 1 | end | 4.120 |
| 1 | 0 | start | 0.550 |
| 1 | 0 | end | 1.550 |
| 1 | 1 | start | 0.430 |
| 1 | 1 | end | 1.420 |
| 2 | 0 | start | 4.100 |
| 2 | 0 | end | 4.512 |
| 2 | 1 | start | 2.500 |
| 2 | 1 | end | 5.000 |
+------------+------------+---------------+-----------+
Output:
+------------+-----------------+
| machine_id | processing_time |
+------------+-----------------+
| 0 | 0.894 |
| 1 | 0.995 |
| 2 | 1.456 |
+------------+-----------------+
Explanation:
There are 3 machines running 2 processes each.
Machine 0's average time is ((1.520 - 0.712) + (4.120 - 3.140)) / 2 = 0.894
Machine 1's average time is ((1.550 - 0.550) + (1.420 - 0.430)) / 2 = 0.995
Machine 2's average time is ((4.512 - 4.100) + (5.000 - 2.500)) / 2 = 1.456
풀이
- activity_type 나누기
- 시간 계산하기 (end - start)
- 평균 구하기
코드
with로 공통의 테이블을 정의한다.
a1은 start를 a2 는 end로 설정하고 각각을 하나의 테이블에 불러와서 호출한다.
이를 불러와 avg로 평균을 계산한다.
이때 소수점 3자리니 round ( _, 3) 해야한다.
machine별로 정의하니, machine_id로 그룹화한다.
with duration as (
select a1.machine_id, a1.process_id, (a2.timestamp - a1.timestamp) as time
from Activity a1
join Activity a2
on a1.machine_id = a2.machine_id
where a1.activity_type = "start" and a2.activity_type = "end"
)
select machine_id, round(avg(time),3) as processing_time
from duration
group by machine_id
링크
LeetCode/1661-average-time-of-process-per-machine at main · K-MarkLee/LeetCode
LeetCode/1661-average-time-of-process-per-machine at main · K-MarkLee/LeetCode
Collection of LeetCode questions to ace the coding interview! - Created using [LeetHub](https://github.com/QasimWani/LeetHub) - K-MarkLee/LeetCode
github.com
'Daily 코드카타 > SQL' 카테고리의 다른 글
코딩테스트 SQL 코드카타 (Project Employees) (0) | 2024.11.26 |
---|---|
코딩테스트 SQL 코드카타 (Employee Bonus) (1) | 2024.11.20 |
코딩테스트 SQL 코드카나 (Rising Temperature) (0) | 2024.11.18 |
코딩테스트 SQL 코드카타 (Customer Who Visited without Any Transactions) (0) | 2024.11.17 |
코딩테스트 SQL 코드카타 (Product Sales Analysis) (0) | 2024.11.17 |