2015-02-12 22 views
2

我有一个查询数据列表的最新记录的要求。这里是我的样品表(主键省略)从给定数据列表中查询最新记录

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程序?

回答

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

你也可以使用一个表表达式

;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 
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; 

如果还有更多的列,将这些列也添加到您的组中。

相关问题