我想选择
data12 [last entry for 12-21-2014],
data11 [last entry for 12-20-2014],
data8 [last entry for 12-19-2014]
从下表。
snapshot_datestamp data
-------------------------------
12-21-2014 08:24:21 data12
12-20-2014 19:58:49 data11
12-20-2014 19:55:36 data10
12-20-2014 19:53:59 data9
12-19-2014 21:56:23 data8
12-19-2014 21:13:16 data7
12-19-2014 11:05:45 data6
12-19-2014 11:05:07 data5
12-19-2014 10:56:13 data4
12-19-2014 10:52:21 data3
12-19-2014 10:50:43 data2
12-19-2014 10:49:30 data1
不太确定如何实现这一点。任何指针都会有很大的帮助。
答案 0 :(得分:1)
简单的方法是使用Order by
和ROWNUM
SELECT *
FROM (SELECT data
FROM tablename
WHERE trunc(snapshot_datestamp) = TO_DATE('12-21-2014','MM-DD-YYYY')
ORDER BY snapshot_datestamp DESC)
WHERE ROWNUM = 1;
答案 1 :(得分:1)
一种方法是每天获取最新时间,然后选择相应的记录:
select
trunc(snapshot_datestamp),
data
from mytable
where snapshot_datestamp in
(
select max(snapshot_datestamp)
from mytable
group by trunc(snapshot_datestamp)
)
order by trunc(snapshot_datestamp);
另一种方法是使用分析函数:
select
trunc(snapshot_datestamp),
max(data) keep (dense_rank last order by snapshot_datestamp)
from mytable
group by trunc(snapshot_datestamp)
order by trunc(snapshot_datestamp);
答案 2 :(得分:1)
假设我们可以在这里使用的数据中没有任何密钥,使用ROW_NUMBER
可能是一个解决方案:
SELECT "snapshot_datestamp", "data" FROM
(
SELECT "snapshot_datestamp", "data",
ROW_NUMBER()
OVER (PARTITION BY TRUNC("snapshot_datestamp")
ORDER BY "snapshot_datestamp" DESC) rn
FROM T
) V
WHERE rn = 1
ORDER BY 1 DESC
这里的想法是为给定日期的每一行编号(根据其“时间戳”以降序排列)。完成后,每个分区的“最后”条目就是该分区中编号为1的行。