2015-02-12 66 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; 

如果還有更多的列,將這些列也添加到您的組中。

相關問題