1. 表结构(TABLE1)
车牌号码,定位时间, 速度, 位置
123 2005-01-01 30 中国
123 2005-03-02 60 中国
456 2005-09-20 30 中国
456 2005-09-30 70 中国2. 需求
每辆车在TABLE1表中可能存在多条记录,现在要求用一SQL语句查询出来各个车最早的那条定位数据。3. 查询结果
车牌号码,定位时间, 速度, 位置
123 2005-01-01 30 中国
456 2005-09-20 30 中国
车牌号码,定位时间, 速度, 位置
123 2005-01-01 30 中国
123 2005-03-02 60 中国
456 2005-09-20 30 中国
456 2005-09-30 70 中国2. 需求
每辆车在TABLE1表中可能存在多条记录,现在要求用一SQL语句查询出来各个车最早的那条定位数据。3. 查询结果
车牌号码,定位时间, 速度, 位置
123 2005-01-01 30 中国
456 2005-09-20 30 中国
from table1
group by 车牌号码,速度,位置
在 车牌号码 和 定位时间 都相同时才会取多条记录。
---------- ----------- ---------- ----------
123 2005-10-10 30 中国
123 2005-10-7 60 中国
456 2005-10-8 20 中国
456 2005-10-1 40 中国Executed in 0.031 secondsSQL> select a1 "车牌号码",a5 "定位时间",a2 "速度",a3 "位置" from
(select a1,a5,a2,a3,rank() over(partition by a1 order by a5) dk from a)
where dk = 1;车牌号码 定位时间 速度 位置
---------- ----------- ---------- ----------
123 2005-10-7 60 中国
456 2005-10-1 40 中国Executed in 0.015 secondsSQL>
(select 速度 from table1 where 车牌号码=t1.车牌号码 and 定位时间=t1.定位时间 and rownumber=1) 速度,
(select 位置 from table1 where 车牌号码=t1.车牌号码 and 定位时间=t1.定位时间 and rownumber=1) 位置
from (select 车牌号码,min(定位时间) 定位时间 from table1 group by 车牌号码)t1
from
(
select 车牌号码,定位时间, 速度, 位置,
row_number()over(partition by 车牌号码 order by 定位时间 asc ) as rn from table1
)
where rn=1;