Wrox Programmer Forums
Go Back   Wrox Programmer Forums > Database > SQL Language
|
SQL Language SQL Language discussions not specific to a particular RDBMS program or vendor.
Welcome to the p2p.wrox.com Forums.

You are currently viewing the SQL Language section of the Wrox Programmer to Programmer discussions. This is a community of software programmers and website developers including Wrox book authors and readers. New member registration was closed in 2019. New posts were shut off and the site was archived into this static format as of October 1, 2020. If you require technical support for a Wrox book please contact http://hub.wiley.com
 
Old May 15th, 2006, 11:09 AM
Registered User
 
Join Date: May 2006
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default Trying to retrieve top 1 for multiple rows

Hi,

There may be a simple solution to my problem but it's got me stumped so hopefully someone can help.

I have a table that has multiple records for units .e.g.
Unit1 Location1 15/05/2006 10:00
Unit1 Location2 15/05/2006 11:00
Unit2 Location1 15/05/2006 12:00
Unit3 Location2 15/05/2006 13:00
Unit3 Location3 15/05/2006 14:00

I'm trying to retrieve the newest record for each unit .e.g.
Unit1 Location2 15/05/2006 11:00
Unit2 Location1 15/05/2006 12:00
Unit3 Location3 15/05/2006 14:00

The only way I’ve manage to pull back the correct data is using nested queries but it's too slow and resource intensive.

Can anyone suggest a query for me?

Thanks,
Monica
 
Old May 15th, 2006, 11:20 AM
Friend of Wrox
 
Join Date: Jun 2003
Posts: 839
Thanks: 0
Thanked 1 Time in 1 Post
Default

When you say 'nested queries' are you referring to a correlated subquery? If a correlated subquery is 'too slow', then you may not have the proper indexes in place.

Did you try:
Code:
    SELECT *
    FROM yourtable T1
    WHERE yourdatetimecolumn
            = (SELECT MAX(yourdatetimecolumn)
                FROM yourtable T2 WHERE T1.UnitColumn = T2.UnitColumn)
This sort of subquery is about as fast as you can get, given appropriate indexes.

Jeff Mason
Custom Apps, Inc.
www.custom-apps.com
 
Old May 16th, 2006, 03:29 AM
Registered User
 
Join Date: May 2006
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Default

Hi Jeff,

Your solution is fantastic!! It's solved a problem I've worked around for ages so thanks very much.

Thanks again,
Monica





Similar Threads
Thread Thread Starter Forum Replies Last Post
SQL to get all rows but top vjs2445 SQL Language 22 May 18th, 2007 06:44 AM
retrieve everything AND count rows in one hit crmpicco MySQL 5 January 20th, 2006 06:02 AM
Getting the Top 5 Rows from a datatable flyin General .NET 9 June 14th, 2004 08:36 AM
Retrieve top 10 bmains XSLT 1 January 5th, 2004 02:54 PM
move rows to top with cells in columnA filled RED alienscript Excel VBA 2 December 2nd, 2003 12:51 PM





Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
Copyright (c) 2020 John Wiley & Sons, Inc.