甲骨文分析 : using LAG values in calculation?

标签 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

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

最佳答案

根据Oracle documentation :

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/

相关文章:

oracle - 从文件服务器中的 oracle 转储文件中提取特定模式

sql - Oracle 日期减法

java - Oracle 11g + hibernate -> ORA-01461 : can bind a LONG value only for insert into a LONG column

sql - 如何使用 oracle SQL 执行线性插值?

sql - 在没有匹配的 JOINed 记录时指定默认值

oracle - 如何查看 Oracle 的 DBMS_PARALLEL_EXECUTE 实用程序完成的错误日志记录?

sql - oracle中的dense_rank()解析函数

MySQL 获取 ORDER BY 编号错误的行位置

分配结果的 SQL 排序