我有一个记录任务完成时间的表格。任务属于工作流,但在此示例中,我只是试图让 LAG 正常工作。
我想查找有关每项任务需要多长时间的信息。
我试过:
select
completed_date,
lag(completed_date) over (order by id) prevrow,
prevrow - completed_date
from
task_complete
where workflow_id = 1
但这会导致错误。有没有办法计算当前行和上一行之间的差异?
最佳答案
Analytic functions are the last set of operations performed in a query except for the final ORDER BY clause. All joins and all WHERE, GROUP BY, and HAVING clauses are completed before the analytic functions are processed. Therefore, analytic functions can appear only in the select list or ORDER BY clause.
这意味着您不能在当前查询级别中使用分析函数的结果。
对此有两种解决方案。您可以根据需要在选择列表中尽可能频繁地包含 LAG
函数。请注意,这就是您即使使用普通函数也会执行的操作,因为无论如何您都无法在同一选择列表的其他地方引用列别名 (prevrow)。
select
completed_date,
lag(completed_date) over (order by id) as prevrow,
lag(completed_date) over (order by id) - completed_date as date_diff
from
task_complete
where workflow_id = 1
或者您可以使用子查询来获取结果:
select
completed_date,
prevrow,
prevrow - completed_date as date_diff
from (
select
completed_date,
lag(completed_date) over (order by id) as prevrow
from
task_complete
where workflow_id = 1
)
关于甲骨文分析 : using LAG values in calculation?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7275334/