列VAL是1到3的数字列表,其他列应该显示:
我希望这个结果:
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
/
有人看到这个查询有什么问题吗?
提前致谢!
答案 0 :(得分:2)
错误位于val preceding
和val following
。它应该是1 preceding
和1 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
/