1661. Average Time of Process per Machine
WITH startCTE as (
SELECT machine_id, process_id, timestamp
FROM Activity
WHERE activity_type = "start"
),
endCTE as (
SELECT machine_id, process_id, timestamp
FROM Activity
WHERE activity_type = "end"
)
SELECT S.machine_id, ROUND(AVG(E.timestamp - S.timestamp), 3) as processing_time
FROM startCTE as S, endCTE as E
WHERE S.machine_id = E.machine_id and S.process_id = E.process_id
GROUP BY 1
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 1
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | SIMPLE | Activity | null | ALL | null | null | null | null | 12 | 50 | Using where; Using temporary |
| 1 | SIMPLE | Activity | null | ALL | null | null | null | null | 12 | 8.33 | Using where; Using join buffer (hash join) |
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | SIMPLE | a1 | null | ALL | null | null | null | null | 12 | 50 | Using where; Using temporary |
| 1 | SIMPLE | a2 | null | ALL | null | null | null | null | 12 | 8.33 | Using where; Using join buffer (hash join) |
USING VS ON
USING
ON
SubQuery VS CTE
SELECT employee_id, first_name, last_name
FROM employees
WHERE department_id = (SELECT department_id FROM departments WHERE department_name = 'Sales');
WITH SalesDepartment AS (
SELECT department_id
FROM departments
WHERE department_name = 'Sales'
)
SELECT employee_id, first_name, last_name
FROM employees
WHERE department_id IN (SELECT department_id FROM SalesDepartment);
재귀적 CTE
자기 자신을 참고하여 반복적으로 데이터를 생성하는 CTE. 계층적인 데이터를 처리하거나, 재귀적인 계산을 수행하는 데 유용하다.
예시 데이터 (employees)

WITH RECURSIVE EmployeeHierarchy AS (
-- Anchor member: 최상위 관리자 선택
SELECT employee_id, manager_id, first_name, last_name, 1 AS level
FROM employees
WHERE manager_id IS NULL
UNION ALL
-- Recursive member: 하위 직원 선택
SELECT e.employee_id, e.manager_id, e.first_name, e.last_name, eh.level + 1
FROM employees e
INNER JOIN EmployeeHierarchy eh ON e.manager_id = eh.employee_id
)
SELECT employee_id, manager_id, first_name, last_name, level
FROM EmployeeHierarchy;
