简体   繁体   English

SQL查询获取最后两条记录的DateDiff

[英]SQL query to get DateDiff of the last two records

I have a table called Event with eventNum as the primary key and date as a datetime2(7) in SQL Server 2008 R2. 我有一个名为Event的表,其中eventNum作为主键,日期作为SQL Server 2008 R2中的datetime2(7)。 I am trying to get the date of the last two rows in the table and get the difference in minutes. 我试图获取表中最后两行的日期,并在几分钟内得到差异。 This is what I currently have: 这就是我目前拥有的:

Select DATEDIFF(MI, e.date,(Select e2.date from Event e2 where eventNum = (Select MAX(e2.eventNum))))
    From Event e
    Where eventNum = (Select MAX(e.eventNum)-1 from e)

and I get this error: 我收到此错误:

Invalid column name 'Select eventNum from Event Where eventNum = Select MAX(eventNum) from Event'. 无效的列名称'从Event中选择eventNum,其中eventNum =从Event中选择MAX(eventNum)。

I've changed this 100 times and can't get it to work. 我已经改变了100次,无法让它发挥作用。 Any help? 有帮助吗?

You could use ROW_NUMBER 你可以使用ROW_NUMBER

WITH CTE AS 
(
   SELECT RN = ROW_NUMBER() OVER (ORDER BY eventNum DESC)
        , date
   FROM Event 
)
SELECT Minutes = DATEDIFF(minute, 
           (SELECT date FROM CTE WHERE RN = 2),
           (SELECT date FROM CTE WHERE RN = 1))

Fiddle: http://www.sqlfiddle.com/#!3/3e9c8/17/0 小提琴: http ://www.sqlfiddle.com/#!3 / 3e9c8/17 /0

This doesn't have to go through the table twice like Tim's answer. 这不必像蒂姆的回答那样经过两次。

select datediff(mi, min(x.date), max(x.date))
from (
    select top(2) *
    from Event e
    order by eventNum desc
) x

在此输入图像描述

Assuming you always have 2 records or more, and the time is monotonously increasing, then the above works. 假设你总是有2个或更多的记录,并且时间单调增加,那么上述工作。

  • If it has only one record, it returns 0 (since max=min=singular record). 如果它只有一条记录,则返回0(因为max = min =单数记录)。
  • If your times are not monotonously increasing, there's a simple tweak to this query 如果你的时间没有单调增加,那么对这个查询进行简单的调整

eg 例如

select top(1) datediff(mi, x.date, y.date)
from event x
join event y on y.eventnum < x.eventnum
order by x.eventnum desc, y.eventnum desc

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM