表结构和数据如下:
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语句表示出来,万分感谢!!
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语句表示出来,万分感谢!!
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 行受影响)
FROM (
SELECT a.* FROM tth4 a
LEFT JOIN (SELECT id,MIN(ctime) AS mi FROM tth4 GROUP BY id) b
ON a.id=b.id AND a.ctime=b.mi WHERE b.id IS NULL) a1
INNER JOIN
(
SELECT a.* FROM tth4 a
LEFT JOIN (SELECT id,MIN(ctime) AS mi FROM tth4 GROUP BY id) b
ON a.id=b.id AND a.ctime=b.mi WHERE b.id IS NULL) a2
ON a1.id=a2.id AND a1.ctime<a2.ctime
SELECT a1.id,TIMEDIFF(MAX(a1.ctime),MIN(a1.ctime)) AS
FROM (
SELECT a.* FROM tth4 a
LEFT JOIN (SELECT id,MIN(ctime) AS mi FROM tth4 GROUP BY id) b
ON a.id=b.id AND a.ctime=b.mi WHERE b.id IS NULL) a1
GROUP BY a1.id
select count(1) from tth4 where id = a.id
and ctime >=a.ctime)<=2
group by id
SET @num=1;
SET @mc='';
SELECT * FROM (
SELECT *,@num:=IF(@mc=id,@num+1,1) AS ss , @mc:=id FROM tth4 ORDER BY id,ctime) a WHERE ss<=2;