Oracle分析:在计算中使用LAG值?

chr*_*ris 2 oracle analytic-functions

我有一张表记录任务完成时间.任务属于工作流程,但在此示例中,我只是尝试让LAG正常工作.

我想找到有关每项任务需要多长时间的信息.

我试过了:

select
  completed_date,
  lag(completed_date) over (order by id) prevrow,
  prevrow - completed_date
from
  task_complete
where workflow_id = 1
Run Code Online (Sandbox Code Playgroud)

但这会导致错误.有没有办法计算当前行和上一行之间的差异?

Mik*_*ers 9

根据Oracle文档:

分析函数是查询中执行的最后一组操作,但最终的ORDER BY子句除外.在处理分析函数之前,将完成所有连接以及所有WHERE,GROUP BY和HAVING子句.因此,分析函数只能出现在选择列表或ORDER BY子句中.

这意味着您无法在查询的当前级别中使用分析函数的结果.

有两种解决方案.您可以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
Run Code Online (Sandbox Code Playgroud)

或者您可以使用子查询来获得结果:

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
)
Run Code Online (Sandbox Code Playgroud)