MYSQL
1、分组取最新的,再用最新的字段连表,回查数据
①按分组字段取最新的,通过主键id回表查数据
- select * from table_name
- WHERE id in (
- select max(id) id from table_name GROUP BY 分组字段)
复制代码 ②非主键字段
- SELECT r.*
- FROM records r
- INNER JOIN (
- SELECT group_id, MAX(timestamp) as latest
- FROM records
- GROUP BY group_id
- ) as latest_records
- ON r.group_id = latest_records.group_id
- AND r.timestamp = latest_records.latest;
复制代码 ORACLE
1、原理解说-可直接看2
筛选出最新的
- SELECT *
- FROM (
- SELECT t.*,
- ROW_NUMBER() OVER (PARTITION BY LOCALAUTHID ORDER BY LASTUPDATETIME DESC) AS rn
- FROM USER_LOCALAUTH_STATE t
- ) t
- WHERE t.rn = 1;
复制代码 解释:
这个序号是基于[LOCALAUTHID]字段举行分区的(即每个[LOCALAUTHID]值都是一个新的分区),而且在每个分区内部,行是按照LASTUPDATETIME字段降序分列的
2、在重复数据取最新的
- SELECT *
- FROM (
- SELECT t.*,ROW_NUMBER() OVER (PARTITION BY LOCALAUTHID ORDER BY LASTUPDATETIME DESC) AS rn
- FROM
- (
- -- 筛选存在重复的数据,count(LOCALAUTHID) > 1
- select * from USER_LOCALAUTH_STATE
- where LOCALAUTHID in (
- SELECT LOCALAUTHID
- FROM USER_LOCALAUTH_STATE WHERE STATE = 1 AND BUSINESSTYPE=1
- group by LOCALAUTHID having count(LOCALAUTHID) > 1)
- ) t
- ) rt
- WHERE rt.rn = 1;
复制代码
3、若要删除不满意条件
在2的基础上,通过[LOCALAUTHID]查询,并删除ID不再2中的
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |