I have a table which looks like this:
. | ID | SystemID | StartDateTime | EndDateTime |
1 | 24 | 1 | 2012-11-09 13:59:00.000 | 2012-11-09 14:23:00.000 |
2 | 25 | 2 | 2012-11-09 13:59:00.000 | 2012-11-09 14:23:00.000 |
3 | 26 | 3 | 2012-11-09 14:00:00.000 | 2012-11-09 14:24:00.000 |
4 | 27 | 1 | 2012-11-09 16:20:00.000 | 2012-11-09 17:19:00.000 |
5 | 28 | 2 | 2012-11-09 16:21:00.000 | 2012-11-09 17:37:00.000 |
6 | 29 | 3 | 2012-11-09 17:25:00.000 | 2012-11-09 17:50:00.000 |
For each system id, I want to select the row that ended closest to and before a given time.
For example if the time was 17:30, the result would look like this:
| ID | SystemID | StartDateTime | EndDateTime |
| 27 | 1 | 2012-11-09 16:20:00.000 | 2012-11-09 17:19:00.000 |
| 25 | 2 | 2012-11-09 13:59:00.000 | 2012-11-09 14:23:00.000 |
| 26 | 3 | 2012-11-09 14:00:00.000 | 2012-11-09 14:24:00.000 |
Hope this makes sense! Thanks for your help.
You could use
outer apply:Live example at SQL Fiddle.