从给定数据列表中查询最新记录

时间:2015-02-12 03:48:48

标签: sql hibernate

我需要查询最新记录以获取数据列表。这是我的样本表(主键省略)

col1| createtime
d1  | 2013-01-31 22:04:15
d1  | 2014-01-31 22:04:15
d1  | 2015-01-31 22:04:15
d2  | 2013-01-31 22:04:15
d2  | 2014-01-31 22:04:15
d2  | 2014-02-31 22:04:15
d2  | 2015-01-31 22:04:15
d3  | 2013-01-31 22:04:15
d3  | 2014-01-31 22:04:15
d3  | 2014-01-31 22:04:15
d3  | 2015-01-31 22:04:15
d4  | 2013-01-31 22:04:15
d4  | 2014-01-31 22:04:15
d4  | 2015-01-31 22:04:15

给出了col1的数据列表。例如,给出的数据列表是[d3,d4]。我的查询结果应该是行

[(d3 2015-01-31 22:04:15),    (d4 2015-01-31 22:04:15)]

因为d3的最新记录是2015-01-31 22:04:15,而d4的最新记录是2015-01-31 22:04:15

这可以不使用sql程序吗?

3 个答案:

答案 0 :(得分:1)

如果您只有两列,请使用group by

select t.col1, max(t.createtime)
from table t
where t.col1 in ('d3', 'd4')
group by t.col1;

如果您有两列以上,我认为以下内容可行:

select t.*
from table t
where t.col1 in ('d3', 'd4') and
      not exists (select 1
                  from table t2
                  where t2.col1 = t.col1 and
                        t2.createtime > t.createtime
                 );

答案 1 :(得分:1)

您还可以使用表格表达式

;WITH C AS(
    SELECT RANK() OVER (PARTITION BY col1 ORDER BY createtime DESC) AS Rnk
           ,col1
           ,createtime
    FROM tableName
)
SELECT col1, createtime FROM C WHERE Rnk = 1

答案 2 :(得分:0)

以下示例可以帮助您解决问题:

select id, max(time_stamp)
  from (select 'd1' as id, '2013-01-31 22:04:15' as time_stamp from dual
        union all
        select 'd1', '2014-01-31 22:04:15' from dual
        union all
        select 'd1', '2015-01-31 22:04:15' from dual
        union all
        select 'd2', '2013-01-31 22:04:15' from dual
        union all
        select 'd2', '2014-01-31 22:04:15' from dual
        union all
        select 'd2', '2014-02-31 22:04:15' from dual
        union all
        select 'd2', '2015-01-31 22:04:15' from dual
        union all
        select 'd3', '2013-01-31 22:04:15' from dual
        union all
        select 'd3', '2014-01-31 22:04:15' from dual
        union all
        select 'd3', '2014-01-31 22:04:15' from dual
        union all
        select 'd3', '2015-01-31 22:04:15' from dual
        union all
        select 'd4', '2013-01-31 22:04:15' from dual
        union all
        select 'd4', '2014-01-31 22:04:15' from dual
        union all
        select 'd4', '2015-01-31 22:04:15' from dual)
 where id in ('d3', 'd4')
 group by id;

如果有更多列,请按字段将这些列添加到您的组中。