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.
| Author |
Topic |
|
harleyquin
Starting Member
2 Posts |
Posted - 2008-07-15 : 05:22:10
|
Hello all, first post here, and I'm not 100% sure if this is the correct forum buit this was arecomended as a good info forum so dont be too harsh on me, I'll probably put too much blerb on but want to be give as much info as possible.I have two tables - one is a master booking, the other is when a customer calledTable AUserID: 1 BookedDate: 01/01/2008 10:00:00UserID: 2 BookedDate: 02/01/2008 11:15:00Table BUserId: 1 CallTime: 01/01/2008 09:59:10UserId: 1 CallTime: 01/01/2008 10:01:00UserId: 1 CallTime: 01/01/2008 10:10:00UserId: 2 CallTime: 01/01/2008 09:50:10UserId: 2 CallTime: 02/01/2008 10:50:10UserId: 2 CallTime: 02/01/2008 11:15:10I know if I do a datediff in seconds I can add find the value in say seconds, I dont think I can use a MIN as I can have positive and negative numbers, where the positive number may be my closest match so to speak from the example above I would expect the return for "closest match to BookedDate"ID1 01/01/2008 09:59:102 02/01/2008 11:15:10I'm floating with the idea of Select top 1 but I'm just not sure how to eloquently code this to return the thrid table with the closest matchanyway thanks for any info provided and if I'm in the wrong place sorry for the post  |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2008-07-15 : 05:35:04
|
[code]DECLARE @TableA TABLE (UserID INT, BookedDate DATETIME)INSERT @TableASELECT 1, '01/01/2008 10:00:00' UNION ALLSELECT 2, '02/01/2008 11:15:00'DECLARE @TableB TABLE (UserID INT, BookedDate DATETIME)INSERT @TableBSELECT 1, '01/01/2008 09:59:10' UNION ALLSELECT 1, '01/01/2008 10:01:00' UNION ALLSELECT 1, '01/01/2008 10:10:00' UNION ALLSELECT 2, '01/01/2008 09:50:10' UNION ALLSELECT 2, '02/01/2008 10:50:10' UNION ALLSELECT 2, '02/01/2008 11:15:10';WITH Yak (UserID, BookedDateA, BookedDateB, RecID)AS ( SELECT a.UserID, a.BookedDate AS BookedDateA, b.BookedDate AS BookedDateB, ROW_NUMBER() OVER (PARTITION BY a.UserID ORDER BY ABS(DATEDIFF(SECOND, a.BookedDate, b.BookedDate))) AS RecID FROM @TableA AS a INNER JOIN @TableB AS b ON b.UserID = a.UserID)SELECT UserID, BookedDateA, BookedDateBFROM YakWHERE RecID = 1[/code] E 12°55'05.25"N 56°04'39.16" |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2008-07-15 : 07:23:01
|
Also this:SELECT t.UserID,tmp.BookedDateFROM @TableA tCROSS APPLY (SELECT TOP 1 BookedDate FROM @TableB ORDER BY ABS(DATEDIFF(ss,t.BookedDate,BookedDate))) tmp |
 |
|
|
harleyquin
Starting Member
2 Posts |
Posted - 2008-07-15 : 12:20:15
|
| Worked a treat - thanks a million :) |
 |
|
|
|
|
|
|
|