无法在Oracle的窗口函数中使用ORDER BY子句

时间:2016-12-17 01:52:52

标签: sql oracle window-functions

我的查询在窗口函数中没有ORDER BY子句时工作正常:

select
"TABLE_NAME",
"DENSITY",
"NUM_DISTINCT",
ROWNUM,
median(DENSITY) OVER (PARTITION BY table_name )
from ALL_TAB_COLUMNS a
where 1=1
and owner = 'SYS'
and table_name='CARRY'
and "NUM_DISTINCT" < 1000
and DENSITY < 1
AND num_nulls = 0

但我绝对需要这个order by子句来获取我需要的格式的数据。如果我添加order by,我会收到这个奇怪的错误消息:

ORA-30487: ORDER BY not allowed here
30487. 00000 -  "ORDER BY not allowed here"
*Cause:    DISTINCT functions and RATIO_TO_REPORT cannot have an ORDER BY
*Action:
Error at Line: 6 Column: 47

以下是带有顺序的完整SQL:

select
"TABLE_NAME",
"DENSITY",
"NUM_DISTINCT",
ROWNUM,
median(DENSITY) OVER (PARTITION BY table_name ORDER BY "DENSITY")
from ALL_TAB_COLUMNS a
where 1=1
and owner = 'DEANZA'
and table_name='CARRIER_A'
and "NUM_DISTINCT" < 1000
and DENSITY < 1
AND num_nulls = 0

1 个答案:

答案 0 :(得分:2)

正如documentation中所述,对于MEDIAN,您无法在其ORDER BY条款中使用OVER

MEDIAN将采用数字或日期时间值并返回中间值或内插值,一旦值已排序,该值将为中间值。所以无论如何都不需要使用ORDER BY