# SQL Interview Questions – Average Time of Process per Machine

### Problem Description –

There is a factory website that has several machines each running the same number of processes. Write an SQL query 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 query result format is in the following example.

## Solution –

``````SELECT
machine_id,
ROUND((SUM(CASE WHEN activity_type = 'end' THEN timestamp END) - SUM(CASE WHEN activity_type = 'start' THEN timestamp END)) / (SELECT COUNT(DISTINCT process_id) FROM Activity),3) as processing_time
FROM Activity
GROUP BY 1
ORDER BY 1``````

Rating: 1 out of 5.

Posted in SQL