Say I had a table like so:
| Timestamp1 | Timestamp2 | Diff | 
|---|---|---|
| 2015-03-17 20:33:00 | 2015-03-17 20:00:00 | 33 | 
| 2015-03-17 20:33:00 | 2015-03-17 21:00:00 | 27 | 
| 2015-03-18 19:17:00 | 2015-03-18 20:00:00 | 43 | 
| 2015-03-18 19:17:00 | 2015-03-18 19:00:00 | 17 | 
Note Diff is calculated as the difference between Timestamp1 and Timestamp2. I would like to use SQL to return the records such that the difference is smallest for records with the same Timestamp1 value.
| Timestamp1 | Timestamp2 | Diff | 
|---|---|---|
| 2015-03-17 20:33:00 | 2015-03-17 21:00:00 | 27 | 
| 2015-03-18 19:17:00 | 2015-03-18 19:00:00 | 17 | 
Also, there could be ties, in which case pick randomly (doesn't matter if actually random or hardcoded).
I've tried following something like this but I'm having trouble with the tie-breaking case where the difference is 30.
 
     
    