生成一个行号并在oracle中每五个客户重复一次

时间:2018-10-09 09:51:08

标签: sql oracle

如何在oracle中为每5个客户生成一个行号? 例如,如果记录数= 10,则预期输出为:1..5,1..5

赞:

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

7 个答案:

答案 0 :(得分:3)

一种解决方案是NTILE分析函数:https://docs.oracle.com/database/121/SQLRF/functions127.htm#SQLRF00680

它还可以很好地处理客户数不能被5整除的情况(例如12个客户)。

示例:

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

答案 1 :(得分:1)

您可以使用模块化算术逻辑,如下所示:

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

答案 2 :(得分:1)

在Oracle中,您可以执行以下操作:

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

您也可以将rownum替换为row_number() over (order by . . . )

答案 3 :(得分:0)

这也有效(oracle);根据您的需要进行更改

选择

“数据”数据列,

rownum original_rownum

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

来自

您的表格;

答案 4 :(得分:0)

我的解决方案使用ROW_NUMBER为每行分配一个值,然后应用MOD函数将其拆分为5。 尽管这可行,但我认为使用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;

答案 5 :(得分:0)

一个简单的模运算就足够了:

SELECT CustomerName, MOD(ROW_NUMBER() OVER (ORDER BY CustomerName) - 1, 5) + 1 AS RN
FROM cte

DB Fiddle

答案 6 :(得分:0)

这可以做到:

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