我有一个名为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)
我收到此错误:
列名无效'从Event Where EventNum =中选择eventNum 从Event'中选择MAX(eventNum)。
我已经改变了100次,无法让它发挥作用。有帮助吗?
答案 0 :(得分:6)
您可以使用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))
答案 1 :(得分:3)
这不需要像蒂姆的回答那样经过两次。
select datediff(mi, min(x.date), max(x.date))
from (
select top(2) *
from Event e
order by eventNum desc
) x
假设您总是有2条或更多条记录,且时间单调增加,那么上述工作就可以了。
e.g。
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