解析函数加窗子句

Posted

技术标签:

【中文标题】解析函数加窗子句【英文标题】:Analytic function windowing clause 【发布时间】:2017-08-18 22:36:53 【问题描述】:

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

A) 所有低于 VAL 的值的最小值 B) 所有低于 VAL 的值的最大值 C) 所有大于 VAL 的值的最小值 D) 最大值 值大于 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】:

错误在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
/

【讨论】:

以上是关于解析函数加窗子句的主要内容,如果未能解决你的问题,请参考以下文章

eval函数解析json数据时加上圆括号

js函数前加感叹号和分号作用

CString构造函数

IIFE(立即执行函数表达式)

C语句详细(初学者)

开源JS代码前面加!,+的意义