Mike Silvis
Mike Silvis

Reputation: 1309

SQL Close By Operator

I have a table that has years 1990 - 2011 in it.

If i have an entry at the year 2007, I want to return the closest year results FIRST. With a limit of say 5 results. So if i have years 2001, 2002, 2005, 2006, 2007, 2008, 2009, 2010, 2011 it would return like this

2007 2008 2006 (order of 2006, and 2008 wouldn't matter, just distance from the year 2007) 2005 2009

Upvotes: 0

Views: 77

Answers (1)

GolezTrol
GolezTrol

Reputation: 116160

Well, order by abs(YEARINTABLE - 2007)

SELECT
  y.Year
FROM
  Years
ORDER BY
  ABS(y.Year - 2007)
LIMIT 5

Upvotes: 4

Related Questions