Oracle-SQL为同一列中具有重复值的行分配相同的row_number

时间:2018-09-24 20:32:38

标签: sql oracle

我有一个表containing FileNameCustomerNameAddress,关系和索引。我想为每行分配一个序列号,但是共享相同地址的同一文件中的两个客户(主要和次要)将需要共享一个序列号,如下所示:

FILE    CUSTOMER    ADDRESS Relationship    INDEX   SEQUENCE
1          A           XX      Primary        1        1
1          B           XX      Secondary      2        1
1          C           XX      Primary        3        2
1          D           XX      Secondary      4        2
1          E           XX      Primary        5        3
1          F           XX      Secondary      6        3

我尝试使用  DENSE_RANK () OVER (PARTITION BY FILE, ADDRESS ORDER BY INDEX) AS SEQUENCE 但是输出仍然没有如上所示。

2 个答案:

答案 0 :(得分:0)

您可以尝试使用lead窗口函数在子查询INDEX中获取下一行ORDER BY Relationship

然后使用SUM窗口函数进行计算。

SELECT 
    "FILE",
    CUSTOMER,
    ADDRESS,
    "INDEX",
    "Relationship",
    SUM(CASE WHEN "INDEX" = 'Primary' AND nextVal = 'Secondary' THEN 1 ELSE 0 END) OVER(ORDER BY "Relationship") SEQUENCE
FROM (
SELECT t1.*,lead("INDEX") OVER (PARTITION BY "FILE", ADDRESS ORDER BY "Relationship") AS nextVal
FROM T t1
) t1

SQLFIDDLE

答案 1 :(得分:0)

我认为您可以将relationship添加到分区列中:

ROW_NUMBER() OVER (PARTITION BY FILE, ADDRESS, RELATIONSHIP ORDER BY INDEX) AS SEQUENCE

请注意,这使用ROW_NUMBER()而不是DENSE_RANK()。领带似乎不是问题。