一个可能的 SQL 版本:
WITH CTE AS(
SELECT ROW_NUMBER()OVER(PARTITION BY [Name] ORDER BY [Time])As RowNum
, *
FROM @table T
)
SELECT
DiffSec=DATEDIFF(s,[Time],(SELECT [Time] FROM CTE c2 WHERE c2.[Name]=CTE.[Name] AND c2.RowNum=CTE.RowNum+1))
, [Name]
, Mood
, [Time]
FROM CTE
ORDER BY [Name],[RowNum]
结果:
DiffSec Name Mood Time
1678 Andy Happy 2012-06-11 14:06:07.000
NULL Andy Sad 2012-06-11 14:34:05.000
5228 Arthur Angry 2012-06-11 14:06:57.000
NULL Arthur Happy 2012-06-11 15:34:05.000
您的测试数据:
declare @table table(name varchar(10),mood varchar(10),time datetime);
insert into @table values('Andy','Happy',convert(datetime,'11.06.2012 14:06:07',104));
insert into @table values('Arthur','Angry',convert(datetime,'11.06.2012 14:06:57',104));
insert into @table values('Andy','Sad',convert(datetime,'11.06.2012 14:34:05',104));
insert into @table values('Arthur','Happy',convert(datetime,'11.06.2012 15:34:05',104));
编辑自加入 aCTE
似乎是一个非常糟糕的主意(“如果你自己加入 CTE,它会杀了你”)。我用临时表中的 500000 条记录测试了我的查询,并在 30 分钟后取消了查询。
这是使用子查询(使用您的注释模式)的更快方法(全部 4 秒):
SELECT T.*
,(SELECT DATEDIFF(s,MAX(T2.Time),T.Time)
FROM dbo.Temp T2
WHERE T2.HE_Id = T.HE_Id
AND T2.Time < T.Time
) AS DiffSec
FROM dbo.Temp AS T
ORDER BY HE_Id ,DiffSec