我有一个表containing
FileName
,CustomerName
,Address
,关系和索引。我想为每行分配一个序列号,但是共享相同地址的同一文件中的两个客户(主要和次要)将需要共享一个序列号,如下所示:
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
但是输出仍然没有如上所示。
答案 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
答案 1 :(得分:0)
我认为您可以将relationship
添加到分区列中:
ROW_NUMBER() OVER (PARTITION BY FILE, ADDRESS, RELATIONSHIP ORDER BY INDEX) AS SEQUENCE
请注意,这使用ROW_NUMBER()
而不是DENSE_RANK()
。领带似乎不是问题。