为了计算每个工序的耗费时间,并找到每个工序的最大和最小耗费时间,同时考虑到工序之间的间隔时间算到下一道工序中,可以使用窗口函数来处理。以下是一个示例 SQL 查询:
```sql
WITH StageTimes AS (
SELECT
job,
oper,
start_time,
end_time,
LEAD(start_time) OVER (PARTITION BY job ORDER BY start_time) AS next_start_time
FROM sfo_transaction_stage
),
OperDurations AS (
SELECT
job,
oper,
start_time,
end_time,
COALESCE(next_start_time, end_time) AS adjusted_end_time,
DATEDIFF(SECOND, start_time, COALESCE(next_start_time, end_time)) AS duration_seconds
FROM StageTimes
)
SELECT
job,
oper,
MIN(duration_seconds) AS min_duration_seconds,
MAX(duration_seconds) AS max_duration_seconds
FROM OperDurations
GROUP BY job, oper
ORDER BY job, oper;
```
### 解释:
1. **StageTimes CTE**:
- 使用 `LEAD` 窗口函数获取相同 `job` 下的下一道工序的 `start_time`。
- 按 `job` 和 `start_time` 进行分区和排序,以确保正确的顺序。
2. **OperDurations CTE**:
- 计算每道工序的调整后的结束时间 `adjusted_end_time`,如果没有下一道工序,则使用原始的 `end_time`。
- 计算每道工序的耗费时间 `duration_seconds`,使用 `DATEDIFF` 函数计算 `start_time` 和 `adjusted_end_time` 之间的秒数。
3. **最终选择**:
- 按 `job` 和 `oper` 分组,计算每个工序的最小和最大耗费时间。
该查询将返回每个 `job` 和 `oper` 的最小和最大耗费时间,考虑到工序之间的间隔时间。
请根据你的实际数据库环境和需求调整查询。如果有更多具体的需求或表结构,请提供详细信息,以便进一步调整查询。