伙计们我有一个名为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] .
我想使用sql的DATEDIFF(interval,start_time,end_time);
函数,但就像现在一样,我被卡住了。非常感谢您的帮助或任何其他选择。
答案 0 :(得分: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;
<强> Example on SQL Fiddle 强>
答案 1 :(得分: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