| Author |
Topic |
|
nick45
Starting Member
1 Post |
Posted - 2005-12-06 : 10:51:40
|
| I have searched the forums and haven't found exactly what I need. Here is my problem:Table Event (ID,EventID,PersonID,... , Date)Table GPS (ID,PersonID, x, y,... , Date)For Table Event, say I have eventID=1, personID=1 was logged at Date='12/05/2005 10:45:33'Table GPS randomly records where PersonID is on 12/05/2005 at these times:10:44:2110:44:5410:45:2110:45:5610:46:20I would like to JOIN the GPS record that is closest in time to the time the event occured (10:45:33) and return x, y. The record I would need to join on is the GPS record logged at 10:45:21. How would I go about doing this?Thanks!Nick. |
|
|
X002548
Not Just a Number
15586 Posts |
Posted - 2005-12-06 : 13:15:49
|
| [code]USE NorthwindGOSET NOCOUNT ONCREATE Table Event ([ID] int,EventID int, PersonID int, [Date] datetime)CREATE Table GPS ([ID] int, PersonID int, x char(1), y Char(1), [Date] datetime)GOINSERT INTO Event([ID], EventID, PersonID, [Date])SELECT 1, 1, 1, '12/05/2005 10:45:33'INSERT INTO GPS([ID], PersonID, x, y, [Date])SELECT 1, 1, 'x', 'y', '10:44:21' UNION ALLSELECT 1, 1, 'x', 'y', '10:44:54' UNION ALLSELECT 1, 1, 'x', 'y', '10:45:21' UNION ALLSELECT 1, 1, 'x', 'y', '10:45:56' UNION ALLSELECT 1, 1, 'x', 'y', '10:46:20'GOSELECT ABS(DATEDIFF(ss,CONVERT(varchar(8),e.[Date],108),g.[Date])) , * FROM Event e JOIN GPS g ON e.PersonID = g.PersonID WHERE ABS(DATEDIFF(ss,CONVERT(varchar(8),e.[Date],108),g.[Date])) = ( SELECT MIN(ABS(DATEDIFF(ss,CONVERT(varchar(8),e2.[Date],108),g2.[Date]))) FROM Event e2 JOIN GPS g2 ON e2.PersonID = g2.PersonID WHERE g2.PersonID = g.PersonID GROUP BY e2.PersonID)GOSET NOCOUNT ONDROP TABLE Event, GPSGO[/code]Brett8-)Hint: Want your questions answered fast? Follow the direction in this linkhttp://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspxAdd yourself!http://www.frappr.com/sqlteam |
 |
|
|
|
|
|