我有一个表格列:
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
答案 0 :(得分:2)
根据您的评论,您的SQL Server版本是2012.所以您可以通过LEAD()
您需要将HH
替换为所需的值
SELECT ID,
UserId,
Serial,
ModifiedDate,
DATEDIFF(HH,ModifiedDate,LEAD(ModifiedDate) over(ORDER BY ID)) AS [Difference]
FROM Times
如果LAG()
由于配置问题而无法在您的数据库上运行,请尝试以下查询。
WITH CTE AS
(
SELECT *,ROW_NUMBER() OVER(ORDER BY CAST(ID AS INT)) AS RN
FROM times
)
SELECT C1.*,DATEDIFF(HH,C1.MODIFIEDDATE,C2.MODIFIEDDATE) AS [DIFFERENCE]
FROM CTE C1 LEFT JOIN CTE C2 ON C1.RN+1 = C2.RN
答案 1 :(得分:1)
用于sql server 2008及更高版本
with cte as
(
select 1 as Id , 1 as UserID, 1111 as Serial, ' 2015-07-20 10:56:53.0000000' as ModifiedDate
union all
select
002, 1, 1111 , '2015-07-21 18:49:24.0000000'
union all
select
003, 1, 1111, '2015-07-22 08:49:23.0000000'
)
,
cte2 as (
select *,
(select min(ModifiedDate) from cte as nextRow where nextRow.Serial = cte.Serial and nextRow.Id > cte.Id) as NextModifiedDate
from
cte
)
select id,USERid,Serial,ModifiedDate,DATEDIFF(SECOND,ModifiedDate,isnull(NextModifiedDate,ModifiedDate)) as Difference
from cte2
此外,您可以直接在表格中使用它
select *
-- ,(select min(ModifiedDate) from Registrations as nextRow where nextRow.Serial = Registrations.Serial and nextRow.Id > Registrations.Id) as NextModifiedDate
, DATEDIFF(second,Registrations.ModifiedDate,
isnull((select min(ModifiedDate) from Registrations as nextRow where nextRow.Serial = Registrations.Serial and nextRow.Id > Registrations.Id),Registrations.ModifiedDate)
) as Difference
from
Registrations
答案 2 :(得分:0)
这适用于2008年,并且在几秒钟内返回更大的差异。
WITH cte AS (SELECT ID, ModifiedDate,
DENSE_RANK() OVER (ORDER BY ID ASC) AS Ranking from Registrations),
SELECT cte1.ID, cte1.ModifiedDate,
DATEDIFF(ss, cte1.ModifiedDate, cte2.ModifiedDate) AS TimeDiff
FROM cte cte1, cte cte2
WHERE cte1.Ranking = cte2.Ranking - 1