Labels

Script categories

Showing posts with label Analytic functions. Show all posts
Showing posts with label Analytic functions. Show all posts

Thursday, 22 September 2011

Analytic functions with Tabibitosan

/*
The requirement for this data;

    4   'pk'
    5,  null  
    6,  null  
    9,  'jk'   
    13, 'jk'   
    14, null

is that a Group identifier be associated with each id,
where the id's form a series.
For example, rows 4, 5 and 6 would form Group 1
whereas 9 would form a group on its own, since
no id precedes it or follows it in a series.
Finally, 13 and 14 would form the final group.

The technique is known as Tabibitosan and has
been well documented by Aketi Jyuuzou in the following thread
https://forums.oracle.com/forums/thread.jspa?threadID=1005478&start=0&tstart=0

*/


-- This is merely an example of the technique;

with t as
(
select 4 id, 'pk' lk from dual union all
select 5,  null  from dual union all
select 6,  null  from dual union all
select 9,  'jk'   from dual union all
select 13, 'jk'   from dual union all
select 14, null  from dual
)
select id, lk, 'LKG'|| dense_rank() over (order by sgroup) lkg_grp
from
    (
    select   id
            ,lk
            ,id - row_number () over (order by id) sgroup
    from t)
order by id;

 ID LK LKG_GRP
--- -- -------
  4 pk LKG1
  5    LKG1
  6    LKG1
  9 jk LKG2
 13 jk LKG3
 14    LKG3
 

Using NULLIF with Analytic functions

-- No zeros wanted in output, instead, must always get the previously non-zero value
with t as
(
select 'a' col1, 1 col2 from dual union all
select 'b', 5 from dual union all
select 'c', 0 from dual union all
select 'd', 0 from dual union all
select 'e', 3 from dual union all
select 'f', 8 from dual union all
select 'g', 0 from dual
)
--
select col1
      ,last_value(nullif(col2,0) ignore nulls)  over (order by col1) col2
from t
order by col1
/

C       COL2
- ----------
a          1
b          5
c          5
d          5
e          3
f          8
g          8