行数计算

Row Number calculation

我希望能够SQL 对下图中的循环列进行编码。如果在 2 分钟内使用了相同的 ID,则它将成为同一循环的一部分。我经常使用 RowNumber() 但不确定它是否那么简单。如果时间在 2 分钟以内,我可以创建一个新的时间列分配相同的数字,但也许有更好的方法。

我确信有更好的方法可以做到这一点,但这是我找到的方法。如果您将 time as integer column 更改为 time as time,那么在 long 运行.

中对您来说会更容易
create table #t (id int, event_time_text nvarchar(6), event_time time);

insert into #t (id,event_time_text) values 
(123456789,'070007'),
(123456789,'070048'),
(123456789,'162455'),
(123456789,'162542'),
(123456789,'184131'),
(123456789,'184207');

update #t set event_time = TIMEFROMPARTS(LEFT(event_time_text,2),SUBSTRING(event_time_text,3,2),SUBSTRING(event_time_text,5,2),0,0);

WITH dat --calculate the difference in minutes of one row from the previous row
AS
(
SELECT *
    ,CASE 
        WHEN DATEDIFF(minute,LAG(event_time,1,event_time) OVER (PARTITION BY id ORDER BY event_time),event_time) <= 2 
        THEN LAG(event_time,1,event_time) OVER (PARTITION BY id ORDER BY event_time) 
        ELSE event_time
     END AS diff_index
FROM #t
)
SELECT *
    ,DENSE_RANK() OVER (PARTITION BY id ORDER BY diff_index) AS group_within_id
FROM dat;

dbfiddle.uk