Link to home
Start Free TrialLog in
Avatar of JDL_Tech
JDL_TechFlag for United States of America

asked on

Select only one matching row via SQL

Given: A Sybase SQL table arranged as "Field1 | Field2 | Field3 ...."

Each Field1 will have one or more Field2's associated with it as shown below.  Field3 is a timstamp.

Field1 | Field2a | Field3
Field1 | Field2b | Field3
Field1 | Field2c | Field3

Selecting a given Field1 would return three rows because of the three different Field2 values.  I need to return exactly one row for each unique Field1.  That row must be the one with the most recent timestamp.

Thank you


Avatar of grant300
grant300

SELECT Field1, SUBSTRING(MAX(CONVERT(CHAR(19),Field3)+Field2),19,128)
  FROM YourTable
 GROUP BY Field1

The trick is to append Field2 on the end of the timestamp so that when you find the MAX of the combined field, you can get back just the Field2 part of it.  This is easiest when both Field2 and Field3 are string data types but you can use the CONVERT function to deal with whatever combination you may have.

Bill
ASKER CERTIFIED SOLUTION
Avatar of awking00
awking00
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial