一张桌子
column1 column2 column3 column4
340 9870 abc mno
338 9870 abc mno
337 3456 abc mno
336 3456 abc mno
335 3456 abc mno
334 3456 abc mno
332 3456 abc mno
331 3456 abc mno
252 2132 abc mno
251 2132 abc mno
249 2132 abc mno
预期产量
column1 column2 column3 column4 column5
340 9870 abc mno 1
338 9870 abc mno 9
337 3456 abc mno 8
336 3456 abc mno 7
335 3456 abc mno 6
334 3456 abc mno 5
332 3456 abc mno 4
331 3456 abc mno 3
252 2132 abc mno 2
251 2132 abc mno 1
249 2132 abc mno 1
当column1中的值按顺序排列时,是否有可能在column3和column4的分区内生成行号,在column2,column1上排序,但是例外情况:在生成行号时,特殊情况下必须将252和331视为顺序。
以下代码无一例外地有效
select t1.*,
row_number() over (partition by column3,column4, column1 - num order by column2,column1 ) as column5
from (select t.*,row_number() over (partition by column3,column4 order by column2,column1) as num
from table1 t
) t1
order by column2 desc,column1 desc
我认为这是一个孤岛问题。假设在252和331之间没有值,则可以lag()
用来确定分组的开始位置,累积总和,以及最终结果是row_number()
该分组上的a 。
我也没有看到以下角色column2
:
select t.*,
row_number() over (partition by column3, column4, grp order by column1) as column5
from (select t.*,
sum(case when prev_column1 is null or
(prev_column1 <> column1 - 1 and
prev_column1 <> 252 and
column1 <> 331
)
then 1 else 0
end) over (partition by column3, column4 order by column1) as grp
from (select t.*,
lag(column1) over (partition by column3, column4 order by column1) as prev_column1
from t
) t
) t;
这是db <>小提琴。
请注意,您的样本数据在333处也有一个中断,此中断会开始。但是,这显示了如何解决您提出的问题。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句