gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 02:04:15 26 4
gpt4 key购买 nike

我有一个名为“Event”的表,其中 eventNum 作为主键,日期作为 SQL Server 2008 R2 中的 datetime2(7)。我试图获取表中最后两行的日期并以分钟为单位获取差异。这是我目前拥有的:

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)

我收到此错误:

Invalid column name 'Select eventNum from Event Where eventNum = Select MAX(eventNum) from Event'.

我已经改变了 100 次,但无法让它工作。有什么帮助吗?

最佳答案

您可以使用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

关于SQL查询获取最后两条记录的DateDiff,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13185869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com