select *
from table t1
where not exists
(select 1
from table t2
where t2.DATETIME < GETDATE()
and t1.DATETIME < t2.DATETIME ---注意,是小于
and t2ROUTEID = 18)
and t1.DATETIME < GETDATE()
and t1.ROUTEID = 18
where 条件后面有错误
select BUSID,max(DATETIME)DATETIMEfrom table
group by BUSID having (DATETIME < GETDATE()
and ROUTEID=18
)
--测试数据
create table bus_table
( id int IDENTITY (1, 1) NOT NULL ,
ROUTEID varchar(10) NULL,
BUSID varchar(10) NULL,
DATETIME DATETIME NULL
)
go
insert into bus_table
select '1','1','2011-05-08 08:59:46'
union all
select '1','2','2011-05-08 09:59:46'
union all
select '18','1','2011-05-08 08:59:46'
union all
select '18','1','2011-05-08 13:59:46'
union all
select '18','2','2011-05-08 11:59:46'
union all
select '18','2','2011-05-08 14:19:46'
union all
select '18','3','2011-05-08 08:59:46'
union all
select '18','3','2011-05-08 13:59:46'
union all
select '18','4','2011-05-08 11:59:46'
union all
select '18','5','2011-05-08 14:19:46'
union all
select '18','3','2011-05-08 13:59:46'
union all
select '18','5','2011-05-08 19:19:46'
go
--SQL语句一
select *
from bus_table a
where id in
(
select top 1 id
from bus_table
where busid=a.busid
and ROUTEID=a.ROUTEID
and DATETIME
order by DATETIME desc
)
ORDER BY ROUTEID,busid,DATETIME