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中的
本文转载自: https://blog.csdn.net/hgg923/article/details/138861593
版权归原作者 多来哈米 所有, 如有侵权,请联系我们删除。
版权归原作者 多来哈米 所有, 如有侵权,请联系我们删除。