I have a database table that contains among other things partial postal codes. I'm trying to write a query that will take a postal code and find the row in the table that matches that code as close as possible. In the example below a Gold customer with postal code 'A1A B2E' would match the first row and a Bronze customer with the same postal code would match the third row
CUST_TYPE | POST_CODE | SHIPPING_SURCHARGE
------------------------------------------
Gold | A1A开发者_JS百科 | 0.99
Gold | A2A | 1.01
Gold | A | 3.00
Bronze | A | 1.05
Silver | A | 1.02
Bronze | B | 1.07
In all cases the query would query by both the CUST_TYPE and the POST_CODE columns. I'd want the query to only return a single row containing the one row that best matches the postal code. So, if I query Gold and 'A1AB2B' I would want the first row (Gold, A1A, 0.99) to be returned not both the first and third rows
SQL-Server
SELECT TOP (1)
*
FROM yourTable
WHERE CUST_TYPE = @cust_type
AND POST_CODE = LEFT( @postal_code, LEN(POST_CODE) )
ORDER BY LEN(POST_CODE) DESC
Oracle
(I can't test now:)
SELECT
*
FROM
( SELECT
*
FROM yourTable
WHERE CUST_TYPE = @cust_type
AND POST_CODE = SUBSTR( @postal_code, 1, LENGTH(POST_CODE) )
ORDER BY LENGTH(POST_CODE) DESC
)
WHERE rownum = 1
You have simply to write a condition as the following:
SELECT * FROM YOUR_TABLE
WHERE CUST_TYPE = Variable_with_cust_type AND
Variable_with_postal_code like '%'||POST_CODE||'%'
You simply concat '%' at the beginning and at the end of the field POST_CODE, and then use the like operator.
I am assuming you are using ORACLE PL/SQL.
精彩评论