I don't understand why there are different results when using an ORDER BY
clause in an analytic COUNT
function.
Using a simple example:
with req as
(select 1 as n, 'A' as cls
from dual
union
select 2 as n, 'A' as cls
from dual)
select req.*, count(*) over(partition by cls) as cnt from req;
gives the the following result:
N CLS CNT
2 A 2
1 A 2
Whereas, when adding an ORDER BY
in the analytic clause, the result is different!
with req as
(select 1 as n, 'A' as cls
from dual
union
select 2 as n, 'A' as cls
from dual)
select req.*, count(*) over(partition by cls order by n) as cnt from req;
CNT column changed:
N CLS CNT
1 A 1
2 A 2
Can someone explain please?
Thanks
First, a link to docs. It's somewhat obscure, however.
Analytic clause consists of
query_partition_clause
,order_by_clause
andwindowing_clause
. And, a really important thing aboutwindowing_clause
isBut not only can you not use
windowing_clause
without theorder_by_clause
, they are tied together.The default windowing clause produces something like running total.
COUNT
returns1
for first row, as there is only one row between the top of the window and the current row,2
for the second row and so on.So in your first query there is no windowing at all, but there is the default windowing in the second one.
And you can simulate the behavior of the first query by specifying fully unbounded window.
Yep