[英]Numbering sequential numbers in a column in SQL
I want to give a number to the value based on value in above row such that when the sequence breaks, it should again start from 1 otherwise should keep on increment the number. 我想给基于上面一行中的值的值一个数字,这样当序列中断时,它应该再次从1开始,否则应该继续增加数字。
The query is : 查询是:
select'30300001' as lst union all
select'30300002' union all
select'30300003' union all
select'30300004' union all
select'30300001' union all
select'30300006' union all
select'30300007' union all
select'30300008' union all
select'30300009'
And the output I want to be as: 我想要的输出是:
select'30300001' as lst,1 as rnk union all
select'30300002',2 union all
select'30300003',3 union all
select'30300004',4 union all
select'30300001',1 union all
select'30300006',1 union all
select'30300007',2 union all
select'30300008',3 union all
select'30300009',4
I tried it with row_number and rank functions but could not get the required output. 我用row_number和rank函数进行了尝试,但无法获得所需的输出。 How can I get the desired result?
如何获得理想的结果?
If you have an orderingid
(of some sort), then you can use the difference between your column and a column with a sequence. 如果您有某种
orderingid
,则可以使用列和具有序列的列之间的差异。 This identifies a group, which can then be used with other window functions: 这将标识一个组,然后可以将其与其他窗口功能一起使用:
select q.*,
row_number() over (partition by grp order by orderingid)
from (select q.*,
(lst - row_number() over (order by orderingid)) as grp
from query q
) q;
Note: this assumes that lst
is actually a number or a value readily converted to a number. 注意:这假设
lst
实际上是一个数字或一个容易转换为数字的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.