34,590
社区成员
发帖
与我相关
我的任务
分享
--如果想要Longitude字段唯一,那就再来个分组。
declare @tb table(PuID int, GpsTime int, Longitude int, Speed int, Rese int)
insert @tb select 1, 1, 3, 1, 0
insert @tb select 1, 2, 4, 2, 0
insert @tb select 2, 3, 5, 3, 0
insert @tb select 2, 4, 6, 4 , 0
insert @tb select 2, 4, 7, 5, 0
insert @tb select 3, 5, 7, 6 , 0
--再嵌套一下,或借用个临时表,速度更快。
select * into #temp from @tb a where not exists(select 1 from @tb where PuID=a.PuID
and (GpsTime>a.GpsTime or (GpsTime=a.GpsTime and Longitude<a.Longitude)))
select PuID,GpsTime,Longitude=max(Longitude),Speed,Rese from #temp
group by PuID,GpsTime,Speed,Rese
drop table #temp
/*
PuID GpsTime Longitude Speed Rese
----------- ----------- ----------- ----------- -----------
1 2 4 2 0
2 4 6 4 0
3 5 7 6 0
(所影响的行数为 3 行)
*/
---测试数据---
if object_id('[RunningStatus]') is not null drop table [RunningStatus]
go
create table [RunningStatus]([PuID] int,[GpsTime] int,[Longitude] int,[Speed] int,[Rese] int)
insert [RunningStatus]
select 1,1,3,1,0 union all
select 1,2,4,2,0 union all
select 2,3,5,3,0 union all
select 2,4,6,4,0 union all
select 2,4,7,5,0 union all
select 3,5,7,6,0
---查询---
select
*
from
[RunningStatus] t
where
not exists(select 1
from RunningStatus
where puid=t.puid
and (GpsTime>t.GpsTime
or GpsTime=t.GpsTime
and (Longitude<t.Longitude
or Longitude=t.Longitude
and Speed>t.Speed)))
---结果---
PuID GpsTime Longitude Speed Rese
----------- ----------- ----------- ----------- -----------
1 2 4 2 0
2 4 6 4 0
3 5 7 6 0
(所影响的行数为 3 行)
--怎么写的这么复杂?这个不就是楼主想要的第一个结果?
declare @tb table(PuID int, GpsTime int, Longitude int, Speed int, Rese int)
insert @tb select 1, 1, 3, 1, 0
insert @tb select 1, 2, 4, 2, 0
insert @tb select 2, 3, 5, 3, 0
insert @tb select 2, 4, 6, 4 , 0
insert @tb select 2, 4, 7, 5, 0
insert @tb select 3, 5, 7, 6 , 0
select * from @tb a where not exists(select 1 from @tb where PuID=a.PuID
and (GpsTime>a.GpsTime or (GpsTime=a.GpsTime and Longitude<a.Longitude)))
/*
PuID GpsTime Longitude Speed Rese
----------- ----------- ----------- ----------- -----------
1 2 4 2 0
2 4 6 4 0
3 5 7 6 0
(所影响的行数为 3 行)
*/