Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

NTILE Function

ArtieboyMar 16 2017 — edited Mar 18 2017

Hi everyone...newbie here...but frequent reader (particularly of Mr. Kulash)

So this is what I want to do:  I want to take a set of rows and group them by a specific # per group  (group 1, group 2, etc.)

In the example here it is a set of five rows per group.  Now in reality I won't know the # of records

But I will know:

the # per group

the total # of "complete groups" (where they all have the same # of records)

and based on that the # of records that go into the final group

with a as

(

select level id from dual connect by level <=101  --create X # of rows

),

b as

(

select id

,5 as per_grp

,ceil(count(id) over ()/5)  as t_buckets   -- total # of buckets needed

,trunc(count(id) over ()/5) as s_buckets -- starting # of buckets

from a

),

c as

(

select id

,per_grp

,t_buckets

,s_buckets

,case when id <= (per_grp * s_buckets) then s_buckets end as m_buckets    --maximum # of complete buckets

from b

)

select

id

,per_grp

,t_buckets

,s_buckets

,m_buckets

,case when m_buckets is not null then ntile(m_buckets) over (partition by m_buckets order by id)

else t_buckets

end as final_grp

from c

The final output would be something like this (I cut down the row #'s)

 

idfinal_grp
11
21
31
41
51
62
72
82
92
102
113
123
133

This seems to work, even if the # of records is less than the grouping #.  I guess I 'm looking for guidance.   Is using the Ntile function in a case statement with a null condition a big mistake?  Would there be a better way of doing this?

I originally started here: 

I'm using:

Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production

PL/SQL Release 11.2.0.3.0 - Production

CORE 11.2.0.3.0 Production

TNS for IBM/AIX RISC System/6000: Version 11.2.0.3.0 - Production

NLSRTL Version 11.2.0.3.0 - Production

Any help would be appreciated.

Cheers!

This post has been answered by Frank Kulash on Mar 16 2017
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Apr 14 2017
Added on Mar 16 2017
10 comments
2,144 views