Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple SQL grouping question

Status
Not open for further replies.

mattjp

Programmer
Sep 23, 2008
11
US
Hi, I'm relatively green at SQL queries, and I was wondering what the best way to construct a t-sql query on this data:

table: activitylog
fields: serial#, starttime, stoptime, activity

'serial' is non-unique, 'serial' + 'starttime' is unique. I need a query that will return, for each serial number, the row with the most recent (greatest) 'starttime' timestamp.

For example, for this table:

SN# start stop act
1234 12:00 12:15 a
1235 13:34 13.45 a
1234 13:50 14:02 b

I need to be able to get:
SN# start stop act
1235 13:34 13.45 a
1234 13:50 14:02 b

What is the best way to do this? Group By doesn't work this way, and I don't think it can be done with a join. Thanks for the help.
 
Check the FAQs at forum183.

"Don't be irreplaceable. If you can't be replaced, you can't be promoted."
 
Code:
SELECT "serial#"
     , starttime
     , stoptime
     , activity
  FROM activitylog 
INNER
  JOIN ( SELECT "serial#"
              , MAX(starttime) AS maxtime
           FROM activitylog
         GROUP
             BY "serial#" ) AS m
    ON m."serial#" = activitylog."serial#"
   AND m.maxtime = activitylog.starttime

r937.com | rudy.ca
 
Thanks--you solved my problem completely!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top