【发布时间】:2016-01-01 15:49:40
【问题描述】:
我有一个表格,列是:
ID UserId Serial ModifiedDate
---- ------ ----- ----------------
我需要计算每行时间戳之间的差异。例如,如果我有这样的表:
ID UserId Serial ModifiedDate
---- ------ ----- ----------------
001 1 1111 2015-07-20 10:56:53.0000000
002 1 1111 2015-07-21 18:49:24.0000000
003 1 1111 2015-07-22 08:49:23.0000000
我需要区分 001 和 002 的时间戳,然后是 002 和 003 的时间戳,结果需要如下:
ID UserId Serial ModifiedDate Difference
---- ------ ----- ---------------- --------
001 1 1111 2015-07-20 10:56:53.0000000
002 1 1111 2015-07-21 18:49:24.0000000
003 1 1111 2015-07-22 08:49:23.0000000
我尝试使用游标来执行此操作,但我找不到在新别名列中获取差异结果的方法。
这是我的查询:
DECLARE @id bigint, @lastmodif datetime2(7), @id2 bigint, @lastmodif2 datetime2(7),@total int;
DECLARE status_cursor CURSOR FOR
SELECT [Id], [ModifiedDate], '0' AS Difference
FROM [Registrations]
where p.Serial = 1111
Order by ModifiedDate
OPEN status_cursor
DECLARE status_cursor2 CURSOR FOR
SELECT [Id], [ModifiedDate],'0' AS Difference
FROM [Registrations]
where p.Serial = 1111
Order by ModifiedDate
OPEN status_cursor2
FETCH NEXT FROM status_cursor2
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM status_cursor INTO @regid, @lastmodif
FETCH NEXT FROM status_cursor2 INTO @regid2, @lastmodif2
SET @total =
(
DATEDIFF(second,@lastmodif,@lastmodif2)
)
UPDATE status_cursor SET Result = @total
【问题讨论】:
-
什么版本的sql server?
-
版本为2012 11.0.5532.0
-
我尝试使用 LEAD 但我收到此消息:未启用并行数据仓库 (PDW) 功能
-
@juanfandres :在我的回答中检查替代解决方案。
标签: sql-server cursor timestamp datediff