4

Guys i have a table that has a column named time. It capture the time of each record entry in to the database. I want to query and return another column displaying the duration between one entry and the entry before it. Example, if i store record for john today at 12:00 pm, and then Ali at 1:10 pm, i want another column that will show 01:10:00 (i.e HH:MM:SS).

I understand i can query each column number as follows.

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

i wanted to query the max row number AS follows but it fails and return error "windowed...."

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

I wanted to use the DATEDIFF(interval,start_time,end_time); function of sql , but as it is now, I am stuck. Please would appreciate your help or any alternative.

4

2 回答 2

2

由于 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;

SQL Fiddle 示例

于 2013-08-20T09:43:02.217 回答
0

您不能将 MAX 应用于 ROW_NUMBER。使用 CTE 并查询。

;WITH MyCTE AS 
(
    SELECT ROW_NUMBER() OVER (ORDER BY [followuptime]) AS RowNum
    FROM [dbo].[FollowUp]
)

SELECT MAX(RowNum)
FROM MyCTE
于 2013-08-20T08:41:37.997 回答