简体   繁体   English

使用 SQL 进行序列编号

[英]Sequence numbering using SQL

I am attempting to sequence units by their arrival time within sql (adhoc) program.我试图通过它们在 sql(adhoc)程序中的到达时间对单元进行排序。 The only program uses calculation (sql script) to create a field.唯一的程序使用计算(sql 脚本)来创建字段。 I have figured I would need to group by incident_number and sort by the earliest arrival_time我想我需要按 event_number 分组并按最早到达时间排序

在 excel 中的样子

My thought is using sequence script, but I am unfamiliar if that would work.我的想法是使用序列脚本,但我不熟悉这是否可行。

Any thoughts?有什么想法吗?

What you are looking for is one of the window functions ROW_NUMBER , DENSE_RANK or RANK (depending on what you want to do in case of ties, if such can occur):您正在寻找的是窗口函数ROW_NUMBERDENSE_RANKRANK (取决于您想在DENSE_RANK情况下做什么,如果可能发生的话):

select
  incident_number,
  apperatus,
  alarm_date,
  arrival_date,
  row_number() over (partition by incident_number order by arrival_date) as sequence
from mytable
order by incident_number, arrival_date;

If you need to order by ascending arrival date with continuous sequence and same sequence number is assigned to multiple occurrences of same incident_number:如果您需要按升序排列具有连续序列的到达日期,并且将相同的序列号分配给多次出现的相同 event_number:

select incident_number, dense_rank() over(partition by incident_number order by 
arrival_date) as sequence_number from table;

If you need to order by descending arrival date with continuous sequence and same sequence number is assigned to multiple occurrences of same incident_number:如果您需要按降序排列具有连续序列的到达日期,并且将相同的序列号分配给多次出现的相同事件编号:

select incident_number, dense_rank() over(partition by incident_number order by 
arrival_date desc) as sequence_number from table;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM