分析函数窗口子句

时间:2017-08-18 22:36:53

标签: oracle analytic-functions

列VAL是1到3的数字列表,其他列应该显示:

  • A)所有低于VAL
  • 的MIN
  • B)MAX值低于VAL
  • C)所有值大于VAL的MIN
  • D)MAX更大 值比VAL

我希望这个结果:

V   A   B   C   D
-------------------
1 |   |   | 2 | 3
2 | 1 | 1 | 3 | 3
3 | 1 | 2 |   | 

但我得到的结果是:

V   A   B   C   D
-------------------
1 |   |   | 2 | 3
2 |   |   |   |  
3 |   |   |   | 

(*)所有空白单元格都是NULL结果

我写的查询:

WITH T AS
       (SELECT     CAST(LEVEL AS NUMBER) val
        FROM       DUAL
        CONNECT BY LEVEL < 4)
SELECT   val
        ,MIN(val) OVER(ORDER BY val RANGE BETWEEN UNBOUNDED PRECEDING AND val PRECEDING) A --MIN_PRECEDING
        ,MAX(val) OVER(ORDER BY val RANGE BETWEEN UNBOUNDED PRECEDING AND val PRECEDING) B --MAX_PRECEDING
        ,MIN(val) OVER(ORDER BY val RANGE BETWEEN val FOLLOWING AND UNBOUNDED FOLLOWING) C --MIN_FOLLOWING
        ,MAX(val) OVER(ORDER BY val RANGE BETWEEN val FOLLOWING AND UNBOUNDED FOLLOWING) D --MAX_FOLLOWING
FROM     T
WHERE    val IS NOT NULL
ORDER BY 1
/

有人看到这个查询有什么问题吗?

提前致谢!

1 个答案:

答案 0 :(得分:2)

错误位于val precedingval following。它应该是1 preceding1 following

您指定的数字是相对于当前记录的,相应于val的记录(按照给定的窗口顺序),因此如果您指定val,那么您将返回(或超前)太远。您应该在当前记录之前(或之后)获得最多/最多一条记录。

所以:

WITH T AS
       (SELECT     CAST(LEVEL AS NUMBER) val
        FROM       DUAL
        CONNECT BY LEVEL < 4)
SELECT   val
        ,MIN(val) OVER(ORDER BY val RANGE BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) A
        ,MAX(val) OVER(ORDER BY val RANGE BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) B
        ,MIN(val) OVER(ORDER BY val RANGE BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING) C
        ,MAX(val) OVER(ORDER BY val RANGE BETWEEN 1 FOLLOWING AND UNBOUNDED FOLLOWING) D
FROM     T
WHERE    val IS NOT NULL
ORDER BY 1
/