Click here to Skip to main content
15,878,970 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have table Articles with next structure:

SQL
ArticleID Price Date
1         50    2010-12-23
1         52    2012-10-22
2         102   2009-02-06
2         95    2007-05-30
2         89    2011-09-12
3         41    2006-01-21
3         63    2012-03-16

I want to get just the articles with latest date, this is implemented with the next SQL query:
SQL
SELECT A1.* FROM (SELECT ArticleID, MAX(Date) AS Latest FROM Articles GROUP BY ArticleID) A2, Articles A1 WHERE A1.ArticleID = A2.ArticleID AND A1.Date =  Latest

The query is working fine, but the retrieving data from the table is going very slow, I have more than 100 000 records in the table. The question is: Can be optimized this query for faster reading from database?
Posted

What about this:

SQL
SELECT TOP 1 * FROM Articles ORDER BY Date DESC
 
Share this answer
 
v2
Comments
Mohamed Mitwalli 24-Oct-12 19:27pm    
5+
fjdiewornncalwe 24-Oct-12 21:49pm    
This won't actually work for the OP because it will only return the top 1 article when the max date from each article is expected.
damodara naidu betha 25-Oct-12 1:44am    
you are right Marcus..
Hi..,

I think following query can help you..

SQL
SELECT A.ArticleId,A.Cost,A.Date FROM 
  (
   SELECT ArticleId,Cost,Date,
   ROW_NUMBER() OVER(PARTITION BY ArticleId ORDER BY Date DESC) ROWNUM 
   FROM Articles
   ) AS A
WHERE A.ROWNUM = 1 



Thank you
 
Share this answer
 
Comments
zlristovski 25-Oct-12 2:33am    
This is OK, but the problem is in that ROW_NUMBER() is not working in ODBC RDB databese, the syntax is very similar as ORACLE but is not same.
damodara naidu betha 25-Oct-12 2:38am    
which database and version you are using ?
zlristovski 25-Oct-12 2:53am    
I am using Oracle Rdb Database v7.2 on OpenVMS Opearting System. To connect to the database from Windows app I'm using Odbc driver from Oracle.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900