有一个表,大概几千行记录,里面有ip 时间 id等一些字段,ip只有几个不重复的值,时间都不同,现在要取出每一个不同ip对应的最近时间的一条记录,能不能只用一个sql语句得出结果。
用开窗函数比较简单 具体如下 :
SELECT * FROM (SELECT ROW_NUMBER() OVER(PARTITION BY ip ORDER BY time DESC) rn, t.* FROM tablename t) WHERE rn = 1 ;
表 abc 字段ip ,时间 date
Select max(ip),(Select max(date) From abc b where date=a.date) date
From abc a
Group by ip
给你写详细一点,望采纳:
表A:
唯一标识 : id ,其他字段:ip ,时间:atime
需求(取到表内”ip”最近一次时间的数据)
----------------------------------------------------------------
第一步:取到所有关于“ip”字段最新一次数据
select ip,max(atime)maxtime from A group by ip
第二步:关联A表取到所有数据
select A.* from A inner join (select ip,max(atime)maxtime from A group by ip)a2 on A.ip=a2.ip and a.time=a2.maxtime
呵呵,何必那么麻烦,一条语句就可以了。
表名table, 最近一次时间的数据,应该使用rowid较大的那一条
select * from table a where not exists (
select 1 from table b where a.ip = b.ip and b.rowid > a.rowid
);
select *
from t
where (ip, dt) in (select ip, max(dt) lastdt from t group by ip)