【问题标题】:Numbering sequential numbers in a column in SQL在 SQL 中对列中的序号进行编号
【发布时间】:2015-12-17 11:35:40
【问题描述】:

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

查询是:

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'

我想要的输出是:

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 

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

【问题讨论】:

  • 您使用的是哪个 dbms?
  • @jarlh 它的 SQL Server 2008
  • SQL 表和结果集代表 无序 集。您需要一列来指定排序。行的顺序是如何定义的?
  • 我列出的订单是基于 ID 列的排序,我没有在这个查询中将其作为问我问题的最小的 sn-p。

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


【解决方案1】:

如果您有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 实际上是一个数字或一个容易转换为数字的值。

【讨论】:

  • 运行此查询将输出为:link,这扰乱了我想要的顺序,并按 ID 排序:link,这显然不是我想要的。
  • @HemantSisodia 。 .只需添加 order by 即可按照您想要的顺序放置。
  • Ordering by ID 给出了我在之前评论的第二个链接中已经显示的输出。它在 ID 为 6 的行上给出的值为 5,而不是将其重置为 1,然后是 2,依此类推。这是我更改的查询: select q.*, row_number() over (partition by grp order by ID) from (select q.*, (lst - row_number() over (order by ID)) as grp from query q ) q order by id 输出为link 这是错误的。
  • order by orderingid.
  • 我只有 orderingid 作为 ID。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多