Skip to content
Advertisement

Assign same group number for N-members in SQL Oracle

let’s say I have only one column of different codes, for example

Code
A
B
.
.
.
Z

I need to add new column with group number and I need it to be dynamic that means sometime I need 10 member group another time 5 member group so the output will be for 5 member group looks like this

code  group
A     1
B     1
C     1
D     1
E     1
F     2
G     2
H     2
I     2
J     2
K     3
.
.
.

of course I am able to to filter the codes so it could end up like this if I have 7 filtered codes

code   group
A      1
D      1
E      1
F      1
K      1
S      2
Z      2

Advertisement

Answer

NTILE analytic function, I’d say. Sample data in lines #1 – 5, query begins at line #6.

SQL> with test (code) as
  2    (select chr(65 + level - 1)
  3     from dual
  4     connect by level <= 26
  5    )
  6  select code,
  7         ntile(5) over (order by code) grp   --> "5" says how many groups you want
  8  from test
  9  order by code;

CODE        GRP
---- ----------
A             1
B             1
C             1
D             1
E             1
F             1
G             2
H             2
I             2
J             2
K             2
L             3
M             3
N             3
O             3
P             3
Q             4
R             4
S             4
T             4
U             4
V             5
W             5
X             5
Y             5
Z             5

26 rows selected.

SQL>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement