急求:最新两行记录的时间字段值之差,非常感谢!

表结构和数据如下:
id ctime
20 2011-05-16 09:30:00
30 2011-05-16 09:10:00
20 2011-05-16 10:30:00
20 2011-05-16 19:30:00
30 2011-05-16 11:30:00
30 2011-05-16 12:30:00


我需要的结果是:
20 9小时
30 1小时

也就是求最新2条时间记录值之差,如何用一条SQL语句表示出来,万分感谢!!

作者: apple749769   发布时间: 2011-05-17

SQL code
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[ctime] datetime)
insert [tb]
select 20,'2011-05-16 09:30:00' union all
select 30,'2011-05-16 09:10:00' union all
select 20,'2011-05-16 10:30:00' union all
select 20,'2011-05-16 19:30:00' union all
select 30,'2011-05-16 11:30:00' union all
select 30,'2011-05-16 12:30:00'
 
---查询---
select id,时间差=datediff(hh,min(ctime),max(ctime))
from(
select *,rn=row_number() over(partition by id order by ctime desc) from tb
)t
where rn between 1 and 2
group by id

---结果---
id          时间差
----------- -----------
20          9
30          1

(2 行受影响)

作者: josy   发布时间: 2011-05-17

引用 1 楼 josy 的回复:
SQL code
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[ctime] datetime)
insert [tb]
select 20,'2011-05-16 09:30:00' union all
select 30,'2011-05-16 ……


+1

作者: AcHerat   发布时间: 2011-05-17

引用 1 楼 josy 的回复:
SQL code
---测试数据---
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([id] int,[ctime] datetime)
insert [tb]
select 20,'2011-05-16 09:30:00' union all
select 30,'2011-05-16 ……

树哥依旧那么犀利。

作者: Zoezs   发布时间: 2011-05-17

非常感谢josy的回复!

我发错了板块,我这个问题是在Mysql环境下,使用select *,rn=row_number() over(partition by id order by ctime desc) from tb进行查询会出错,不知道有哪位兄弟知道在Mysql中的类似实现?谢谢!

作者: apple749769   发布时间: 2011-05-17