Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 how to join two tables and dynamically select top 1 ordered by date in the second table?

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2003-10-24 : 08:27:57
boo writes "I have two tables joined by a common GUID, let’s say the UserID, and the tables are User and UserHistory. The first table has information about the user, where the second table is a log of actions that a user may take.

I want to do a query so that I get all the users, with just the top 1 ordered by datecreated desc in the second table. My result set should look something like this:

User Last Action
Ted Logon
Bob Logoff

I’m not sure how to dynamically select the top 1 by UserID and order it descending when I don’t know the UserID before hand. This should be simple, but I’m stumped. Please help! Thanks."

LarsG
Constraint Violating Yak Guru

284 Posts

Posted - 2003-10-24 : 08:51:33
[code]
select username, action
from u , uh where u.userid = uh.userid
and uh.datecreated = (select max(datecreated)
from uh
where userid = u.userid)
[/code]

Change names as apropriate.
Go to Top of Page

Stoad
Freaky Yak Linguist

1983 Posts

Posted - 2003-10-24 : 08:57:20
... or

select User,
(select top 1 Action from UserHistory t where t.UserID=Users.UserID
order by datecreated desc) as LastAction
from Users
Go to Top of Page
   

- Advertisement -