我是sql server的新手。有没有办法可以比较前两行的时间?我的ID是唯一的,所以如果我添加另一个时间我想要相同而不改变我的查询的值。如果我的问题不明确,我想知道最后2行的时差。抱歉。
答案 0 :(得分:0)
您可以直接比较日期,就像它们是数字一样。
SELECT id FROM table WHERE time >= '2016-07-15'
要获得两次之间的差异,请使用DATEDIFF
http://www.techonthenet.com/sql_server/functions/datediff.php
答案 1 :(得分:0)
您可以在下面的解决方案中提出十几种变体。如果你能理解它们,那么你将在这个过程中学到很多SQL。
-- scalar subqueries
select datediff(second, max("time"), (select max("time") from T)) as difference
from T
where "time" < (select max("time") from T)
-- correlated subquery
select datediff(
second,
(select t2."time" from T as t2 where t2."time" < t."time"),
t."time") as difference
from T as t
where t.id = (select max(id) from T)
-- self outer joins
select datediff(second, max(t2."time"), max(t."time")) as difference
from T as t left outer join T as t2 on t2."time" < t."time" -- by time
select datediff(second, max(t2."time"), max(t."time")) as difference
from T as t left outer join T as t2 on t2.id = t.id - 1 -- by id
-- cross apply
select datediff(second, max(prev."time"), max(t."time")) as difference
from T as t cross apply
(select max("time") from T as t2 where t2."time" < t."time") as prev("time")
-- cte with case expression
with max_time("time") as (select max("time") from T)
select min(case when t."time" <> max_time."time"
then datediff(second, t."time", max_time."time") end) as difference
from T as t cross apply max_time
-- derived table and analytic functions
select difference
from (
select
row_number() over (order by "time" desc) as rn,
datediff(second, lag("time") over (order by "time"), "time") as difference
from T
) T2
where rn = 1