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 |
dextrous
Starting Member
15 Posts |
Posted - 2009-07-30 : 03:15:27
|
Hello,I have a huge database of US Zip-codes (Zip as well as zip+4).Each row has some data about the zip-code (income, population, total, etc.). There's a cluster index on the zipcode.Right now the use for this db is with a simple application I'm developing:When a user supplies a zipcode in a csv file, the data is read and the output appends the zip code information from the db onto the file.So, if user gives 94122-1111, the query matches 94122-1111 in the db and pastes all relevant information into the file.The problem is when a user gives 94122-1108...and there's no match for it as we may not have information for that zipcode because its new or just an office zipcode, etc. In these instances, I want to display the closest numeric match instead. So, if we we have 94122-1111 but not 94122-1108, I want to display that.Is there an easy way to find the closest numeric match? Thanks  |
|
asgast
Posting Yak Master
149 Posts |
|
dextrous
Starting Member
15 Posts |
Posted - 2009-07-30 : 16:23:18
|
Hi,What if we considered them as numbers, "941221111"...is it possible to find the "closest match" to numerical values? |
 |
|
X002548
Not Just a Number
15586 Posts |
Posted - 2009-07-30 : 16:48:41
|
quote: Originally posted by dextrous Hi,What if we considered them as numbers, "941221111"...is it possible to find the "closest match" to numerical values?
Sure...here's a way to find to closest one before and the closest one aftercut and paste the code to see it workCREATE TABLE #zip(zip4 varchar(10))GOINSERT INTO #zip(zip4)SELECT '94122-1099' UNION ALLSELECT '94122-1100' UNION ALLSELECT '94122-1111' UNION ALLSELECT '94122-1112' UNION ALLSELECT '94122-1113'GOSELECT * FROM #zipGODECLARE @inputzip intSET @inputzip = '941221108'SELECT MAX(CONVERT(int,REPLACE(zip4,'-',''))) AS zip_BEFORE FROM #zipWHERE CONVERT(int,REPLACE(zip4,'-','')) < @inputzipUNION ALLSELECT MIN(CONVERT(int,REPLACE(zip4,'-',''))) AS zip_AFTER FROM #zipWHERE CONVERT(int,REPLACE(zip4,'-','')) > @inputzipGODROP TABLE #zipGO Brett8-)Hint: Want your questions answered fast? Follow the direction in this linkhttp://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspxAdd yourself!http://www.frappr.com/sqlteam |
 |
|
dextrous
Starting Member
15 Posts |
Posted - 2009-07-30 : 17:06:39
|
Great, thank you! |
 |
|
|
|
|
|
|