[英]Generate a rownumber and repeat every five customers in oracle
How to generate a row number for every 5 customers in oracle? 如何在oracle中为每5个客户生成一个行号? For example, if number Of records = 10 the expected output would be:
1..5,1..5
例如,如果记录数= 10,则预期输出将是:
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 一种解决方案是
NTILE
分析功能: 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). 它也很好地处理了客户数不能被5整除的情况(例如12个客户)。
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
)
);
In Oracle, you can just do: 在Oracle中,您可以执行以下操作:
select t.*, 1 + mod(rownum - 1, 5) as rownumber
from t;
You can replace rownum
with row_number() over (order by . . . )
as well. 您也可以将
rownum
替换为row_number() over (order by . . . )
。
this also works (oracle); 这也适用(oracle); alter this according to your needs
根据您的需要更改
select 选择
'data' data_column, 'data'data_column,
rownum original_rownum, rownum original_rownum,
replace(mod(rownum,5),0,5) expected_rownum replace(mod(rownum,5),0,5)Expected_rownum
from 从
your_table; 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. 我的解决方案使用ROW_NUMBER为每行分配一个值,然后应用MOD函数将其拆分为5。 Whilst this works I think the other solution using NTILE is cleaner.
尽管这可行,但我认为使用NTILE的其他解决方案更干净。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.