计算sql中条目之间的时间

伙计们我有一个表有一个名为time的列.它捕获每个记录条目进入数据库的时间.我想查询并返回另一列,显示一个条目和它之前的条目之间的持续时间.例如,如果我今天中午12点为约翰存储记录,然后在下午1:10存储阿里,我想要另一列显示01:10:00(即HH:MM:SS).

据我所知,我可以按如下方式查询每个列号.

SELECT ROW_NUMBER() OVER (ORDER BY [followuptime]) from [dbo].[FollowUp] .

我想查询最大行号AS,但它失败并返回错误“windowed ….”

SELECT MAX(ROW_NUMBER() OVER (ORDER BY [followuptime])) from [dbo].[FollowUp] .

我想使用DATEDIFF(interval,start_time,end_time); sql的功能,但就像现在一样,我被卡住了.非常感谢您的帮助或任何其他选择.

最佳答案 由于SQL-Server 2008R2不支持LAG / LEAD,因此您需要使用row_number进行自联接以获取上一行的时间:

WITH OrderedResults AS
(   SELECT  [id],
            [followuptime],
            [remark],
            RowNumber = ROW_NUMBER() OVER (ORDER BY [followuptime]) 
    FROM    [dbo].[FollowUp]
)
SELECT  a.ID, 
        a.FollowUpTime, 
        a.Remark, 
        PreviousTime = b.FollowUpTime,
        MinutesDifference = DATEDIFF(MINUTE, b.FollowUpTime, a.FollowUpTime)
FROM    OrderedResults a
        LEFT JOIN OrderedResults b
            ON b.RowNumber = a.RowNumber - 1
ORDER BY a.FollowUpTime;

Example on SQL Fiddle

点赞