2

Oracle 的一些分析函数允许使用窗口子句指定当前分区的子集,使用诸如“无界前/后”、“当前行”或“value_expr 前/后”之类的关键字,其中 value_expr 是物理或逻辑偏移量当前行或值(取决于您是否分别指定了 ROW 或 RANGE)。

这是一个使用 scott/tiger 的示例,它显示部门 30 中的员工,以及在他们之前雇用的部门中的员工数量(包括他们自己):

select deptno, 
       empno,
       hiredate,
       count(*) over (partition by deptno 
                          order by hiredate
                          range between unbounded preceding and current row) cnt_hired_before1,
       count(*) over (partition by deptno 
                          order by hiredate
                          range between unbounded preceding and 0 preceding) cnt_hired_before2
  from emp
 where deptno = 30
 order by deptno, hiredate;

...任何人都可以提供“当前行”不同于“0前/后”的示例或文档吗?对我来说,这似乎是语法糖......

4

3 回答 3

2

It doesn't really matter which you use. They are two different ways of expressing the windowing, but the optimizer will perform the query the same way. The term "current row" is one that is common to multiple databases with analytic functions, not just Oracle. It's more of a stylistic difference, in the same way that some people prefer count(*) over count(1).

于 2008-12-29T21:46:20.317 回答
1

我必须提供的 Oracle 文档(Oracle 9.2)说:

如果您指定范围:

  • value_expr 是一个逻辑偏移量。它必须是一个常数或表达式,计算结果为正数值或区间文字。

这意味着您不应该真正使用 0,因为它不是一个正数值。但是,显然可以使用 0 之前/之后,因为你是。

于 2008-12-19T16:52:17.640 回答
-1

这完全取决于您要完成的工作。您可能希望使用 RANGE BETWEEN/ROWS BETWEEN 使用它来查找子集中的 LAST_VALUE 或比较子集中的事物。但是您提供的示例肯定不需要。

    select deptno, 
       empno,
       hiredate,
       count(*) over (partition by deptno, trunc(hiredate,'mm')) cnt_same_month
  from emp
 where deptno = 30
 order by deptno, hiredate
于 2008-12-18T23:16:29.367 回答