SQL查询每天最新记录
我有一个 Oracle 10g 数据库,其中有一个表,其结构和内容与以下内容非常相似:
CREATE TABLE MyTable
(
id INTEGER PRIMARY KEY,
otherData VARCHAR2(100),
submitted DATE
);
INSERT INTO MyTable VALUES (1, 'a', TO_DATE('28/04/2010 05:13', ''DD/MM/YYYY HH24:MI));
INSERT INTO MyTable VALUES (2, 'b', TO_DATE('28/04/2010 03:48', ''DD/MM/YYYY HH24:MI));
INSERT INTO MyTable VALUES (3, 'c', TO_DATE('29/04/2010 05:13', ''DD/MM/YYYY HH24:MI));
INSERT INTO MyTable VALUES (4, 'd', TO_DATE('29/04/2010 17:16', ''DD/MM/YYYY HH24:MI));
INSERT INTO MyTable VALUES (5, 'e', TO_DATE('29/04/2010 08:49', ''DD/MM/YYYY HH24:MI));
我需要做的是查询数据库以获取在每一天提交的最新记录。例如,对于上述数据,我希望返回 ID 号为 1 和 4 的记录,因为它们分别是 4 月 28 日和 4 月 29 日的最新记录。
不幸的是,我对 SQL 缺乏专业知识。有人可以提供一些关于如何实现这一目标的见解吗?
提前致谢!
I've got an Oracle 10g database with a table with a structure and content very similar to the following:
CREATE TABLE MyTable
(
id INTEGER PRIMARY KEY,
otherData VARCHAR2(100),
submitted DATE
);
INSERT INTO MyTable VALUES (1, 'a', TO_DATE('28/04/2010 05:13', ''DD/MM/YYYY HH24:MI));
INSERT INTO MyTable VALUES (2, 'b', TO_DATE('28/04/2010 03:48', ''DD/MM/YYYY HH24:MI));
INSERT INTO MyTable VALUES (3, 'c', TO_DATE('29/04/2010 05:13', ''DD/MM/YYYY HH24:MI));
INSERT INTO MyTable VALUES (4, 'd', TO_DATE('29/04/2010 17:16', ''DD/MM/YYYY HH24:MI));
INSERT INTO MyTable VALUES (5, 'e', TO_DATE('29/04/2010 08:49', ''DD/MM/YYYY HH24:MI));
What I need to do is query the database for the latest record submitted on each given day. For example, with the above data I would expect the records with ID numbers 1 and 4 to be returned, as these are the latest each for 28 April and 29 April respectively.
Unfortunately, I have little expertise as far as SQL is concerned. Could anybody possibly provide some insight as to how to achieve this?
Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会使用公共表表达式(又名 CTE),如下所示:
I would use a common table expression (aka CTE) like so:
我认为这很简单:
SELECT * from MyTable ORDER BY Submitted DESC LIMIT 1
尽管可能值得探索是否有一些列/where 参数可以使查询运行得更快,特别是如果您有一个方便的查询计划分析器。
I think it's as simple as:
SELECT * from MyTable ORDER BY submitted DESC LIMIT 1
Though it might be worth exploring whether there are some column/where parameters that could make the query run more quickly, particularly if you've got a query plan analyzer handy.