|
|
|||||||||
|
|||||||||
| |||||||||
|
|
|
| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Rate Thread | Display Modes |
|
#1
|
|||
|
|||
|
Most Recent entry for a particular record
Hi all,
I'm having troubles finding the best way to do this so here is the problem: Table Users ID UserName 1 Jim 2 Bob 3 Jane 4 Mary Table History ID UserID StatusID InsertDate 1 1 1 2008-01-01 2 2 1 2008-01-01 3 3 1 2008-01-01 4 4 1 2008-01-01 5 1 1 2008-01-02 6 2 1 2008-01-02 7 3 2 2008-01-02 8 4 2 2008-01-02 9 1 1 2008-01-03 10 2 1 2008-01-03 Table StatusMessage ID Message 1 "Good" 2 "Bad" Now what I need is a query that gets me the Status Message for the most recent History entry for each user. So for the example above I need the results Jane "Bad" 2008-01-02 Mary "Bad" 2008-01-02 Jim "Good" 2008-01-03 Bob "Good" 2008-01-03 does this make sense? |
|
#2
|
|||
|
|||
|
Code:
select username,
message,
insertDate
from users
join history on users.id = history.userid
join statusmessage on history.statusid = statusmessage.id
where insertDate =
(select max(insertDate)
from history as h
where h.userid = history.userid)
|
|
#3
|
|||
|
|||
|
Quote:
SELECT U.UserName, S.Message, MAX(H.InsertDate) From User U INNER JOIN History H ON U.ID = H.UserID Inner JOIN StatusMessage S ON H.StatusID = S.ID GROUP BY U.UserName,S.Message |
|
#4
|
||||
|
||||
|
Quote:
![]() that will get max date for each message for each user if the user has 3 different messages sent on 5 days (two of them as repeats) then your query returns 3 rows for that user this is not the same as getting the latest message for each user |
|
#5
|
|||
|
|||
|
Whoops.... your right, I obviously wasn't thinking properly
|
|
#6
|
||||
|
||||
|
tip: don't try to improve upon any solution posted by swampboogie
![]() |
|
#7
|
|||
|
|||
|
Much appreciated.
Thanks. |
![]() |
| Viewing: Dev Shed Forums > Databases > MS SQL Development > Most Recent entry for a particular record |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|