| Author |
Topic |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2007-01-11 : 06:51:51
|
| Leo writes "Hi,I have an interesting case with two tables.Table1 exist of columns: ID, name, activeTable2 exist of columns: ID, event, datetimeID fields matchTable 1 holds data for each user.Exmaple data:1, john doe1, 12, john doe2, 13, john doe3, 04, john doe4, 1Table 2 hold data for all events (event is an integer 1, 2, 3, 4, 5, 6 or 7).Example data:3, 7, 01/10/2004 5:00 PM1, 1, 11/03/2006 11:30 AM4, 7, 10/02/2006 9:01 AM2, 4, 10/31/2006 11:32 AM1, 5, 12/03/2006 11:31 AM4, 2, 10/01/2006 9:01 AMI need to get the latest event for each ID that is active in table1. Example output (based on the above example data):john doe1, 5, 12/03/2006 11:31 AMjohn doe2, 4, 10/31/2006 11:32 AMjohn doe4, 7, 10/02/2006 9:01 AM How to achieve this?(ms sql, windows 2000)" |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-01-11 : 06:56:09
|
| [code]SELECT x.Name, t.Event, x.dtFROM ( SELECT t1.ID, t1.Name, MAX(t2.DateTime) AS dt FROM Table1 AS t1 INNER JOIN Table2 AS t2 ON t2.ID = t1.ID WHERE t1.Active = 1 GROUP BY t1.ID, t1.Name ) AS xINNER JOIN Table2 AS t ON t.ID = x.ID AND t.DateTime = x.dtORDER BY x.Name[/code]Peter LarssonHelsingborg, Sweden |
 |
|
|
l.mourits
Starting Member
1 Post |
Posted - 2007-01-11 : 08:04:22
|
Wow, that is a swift reply And, it works thanks big time |
 |
|
|
|
|
|