I’m trying to select a set of dates that is closest to (including before and after) a specific date.
I’m pretty close, all I want to do now is select the top 10 ‘Closeness’ to 0… but I’m not sure how to do that.
BEGIN
Declare @DateCenter datetime2 = '2011-03-30 00:15:00'
Declare @DateStart datetime2 = DATEADD(day,-7,@DateCenter)
Declare @DateEnd datetime2 = DATEADD(day,7,@DateCenter)
SELECT TOP 30 *, DateDiff(hour, Utc, @DateCenter) as Closeness
FROM [CheckIns]
WHERE Utc BETWEEN @DateStart AND @DateEnd
END
10 or 30, you’re narrative and code sample don’t match. Anyhow, the following should work:
this doesn’t distinguish between those before and those after – it simply seeks the 10 closest. If you wanted, say, the 10 that precede a date, and the 10 that succeed it, then you’d need 2 orderings, or possibly a
PARTITION BYclause also to theROW_NUMBERwindow function.If you wanted to include tied results, you’d need to switch to using
RANK()orDENSE_RANK()instead ofROW_NUMBER().