查询最大时间或者排名最前的数据

查询最大时间或者排名最前的数据

三种方法
第一种

select * from t_company t RIGHT JOIN 
(select type, MAX(create_date) as "createDate" from t_company GROUP BY type) tmp 
on t.create_date = tmp.createDate and t.type=tmp.type

另一种查询思路是采用子查询的方式,将类型type作为子查询查询块的条件,取最大的创建时间create_date,然后再用子查询查询块得到的最大时间作为查询条件,这样就相当于分别查询每种类型(type)最大时间的那条数据

select * from t_company t where t.create_date = (select max(t2.create_date) from t_company t2 where t2.type = t.type)  

一个常见的方法是先对数据进行排序,然后再进行分组,以此来获取每组的第一条记录。这可以通过在子查询中使用ORDER BY来实现,然后在外层查询中使用GROUP BY。例如:

SELECT * FROM (
SELECT DISTINCT(a.id) tid, a.*
FROM template_detail a
WHERE a.template_id IN (3, 4)
ORDER BY a.id DESC
) tt
GROUP BY tt.template_id;

窗口函数方法


SELECT *
FROM (
    SELECT *,
        ROW_NUMBER() OVER (
            PARTITION BY group_column 
            ORDER BY time_column DESC
        ) AS rn
    FROM your_table
) ranked
WHERE rn = 1;
posted @ 2025-08-29 18:10  赏金猎人小熊  阅读(9)  评论(0)    收藏  举报