在SQL中的列中对序列号进行编号

时间:2015-12-17 11:35:40

标签: sql sql-server sql-server-2008 tsql

我想根据上面一行中的值给出一个数字,这样当序列中断时,它应该从1开始,否则应该继续增加数字。

查询是:

         psutil.net_io_counters()

我希望输出为:

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'

我尝试使用row_number和rank函数但无法获得所需的输出。我怎样才能得到理想的结果?

1 个答案:

答案 0 :(得分:0)

如果您有orderingid(某种),那么您可以使用列与列之间的差异与序列。这标识了一个组,然后可以与其他窗口函数一起使用:

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;

注意:这假设lst实际上是一个数字或一个容易转换为数字的值。