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 strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL aggregate query help needed

Status
Not open for further replies.

davidib

Technical User
Feb 10, 2005
13
GB
I have a database table that contains three columns: var_name, var_value and timestamp. var_name and var_value are both integers and timestamp is a date/time field. There are many rows for each value of var_name containing a different var_value and the timestamp is when the row was written.

I need a single SQL query that will return me the latest var_value for each var_ref in the table but my SQL skills aren't good enough for the task! Can someone help?

Thanks
 
davidib said:
...table contains three columns: var_name, var_value and timestamp...
need latest var_value for each var_ref...
Where does var_ref come from?

Code:
select var_ref,var_value 
from yourtable a join 
(select var_name as var_ref,max(timestamp) timestamp 
 from yourtable group by var_name
) b
on a.var_name=b.var_ref
 and a.timestamp=b.timestamp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top