I'm working on this problem from LeetCode.com:
Column Name Type machine_id int process_id int activity_type enum timestamp float
The table shows the user activities for a factory website. (machine_id, process_id, activity_type) is the primary key (combination of columns with unique values) of this table. machine_id is the ID of a machine. process_id is the ID of a process running on the machine with ID machine_id. activity_type is an ENUM (category) of type ('start', 'end'). timestamp is a float representing the current time in seconds. 'start' means the machine starts the process at the given timestamp and 'end' means the machine ends the process at the given timestamp. The 'start' timestamp will always be before the 'end' timestamp for every (machine_id, process_id) pair.
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.
I was able to solve this problem using a self join, but I found the best practices say to avoid self joins and instead use window functions. However, I can't figure out how I would do this (if it is possible).
I'm able to solve the problem with a self join as follows:
select a1.machine_id, round(avg(a2.timestamp-a1.timestamp), 3) as processing_time
from Activity a1
join Activity a2
on a1.machine_id=a2.machine_id and a1.process_id=a2.process_id
and a1.activity_type='start' and a2.activity_type='end'
group by a1.machine_id
I also am able to start a window function like this:
SELECT a1.machine_id, AVG(a1.timestamp) OVER (PARTITION BY machine_id) AS processing_time
FROM Activity AS a1
But is it possible to do a row-level calculation to subtract the times while aggregating these averages? Also, my above code (2nd block) doesn't work when I add group by a1.machine_id to the bottom. Can anyone explain why? Here's the specific error:
[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Column 'Activity.timestamp' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. (8120) (SQLExecDirectW)