简体   繁体   中英

Generate a rownumber and repeat every five customers in oracle

How to generate a row number for every 5 customers in oracle? For example, if number Of records = 10 the expected output would be: 1..5,1..5

Like this:

CustomerName  Row Number  
A                 1  
B                 2  
C                 3  
D                 4  
E                 5  
F                 1  
G                 2  
H                 3  
I                 4  
J                 5

one solution would be the NTILE analytic function: https://docs.oracle.com/database/121/SQLRF/functions127.htm#SQLRF00680

It also deals nicely with cases where the number of customers is not divisible by 5 (eg 12 customers).

Sample:

with customers as (        
    select level customername from dual connect by level <= 10)
select customername, ntile(5) over (order by customername asc) rownumber
from customers;  

You may use modular arithmetical logic as below :

select "Customer Name", replace(mod(rn,5),0,5) "Row Number"
  from
(
  select CustomerName as "Customer Name", row_number() over (order by CustomerName) as rn
    from
  (
    select chr(level+64) CustomerName, level as nr
      from dual
     connect by level <= 10 
  )
);

Rextester Demo

In Oracle, you can just do:

select t.*, 1 + mod(rownum - 1, 5) as rownumber
from t;

You can replace rownum with row_number() over (order by . . . ) as well.

this also works (oracle); alter this according to your needs

select

'data' data_column,

rownum original_rownum,

replace(mod(rownum,5),0,5) expected_rownum

from

your_table;

My solution uses ROW_NUMBER to assign a value to each row and then applies the MOD function to split it into 5's. Whilst this works I think the other solution using NTILE is cleaner.

WITH cust AS
  (SELECT customername, ROW_NUMBER() OVER(ORDER BY customer_name) AS ordering
   FROM customers)
SELECT customername , CASE WHEN MOD(ordering,5) = 0 THEN 5 ELSE MOD(ordering,5) END AS bucket
  FROM cust;

this will do:

select e.*, mod(rownum-1,5)+1 rownumber
from (select * from table_name) e;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM