简体   繁体   中英

SQL, joining the same table

I have a table with the columns code and document . The column code may have alphanumeric values (only letters) and/or numeric values (only digits). In the model, every numeric code has an alphanumeric equivalent code . The records below represent an example of this situation (in the form ( document , code );( document , code ):

(12345678900,ABC);(12345678900,999)

But, a alphanumeric code may not always have a equivalent numeric code , so the example below represents a situation where we have 3 different records

(12345678900,ABC);(12345678900,999);(00987654321,XYZ);(11111111111,DEF)

With this in mind, what I want to do is the following: what I'll use to search records is always alphanumeric code s, and when I have an equivalent numeric, I want as result the numeric one, but when the alpha doesn't have the numeric equivalent, I want the alphanumeric code .

For instance, if I execute the following selects, I would get the results below:

  1. SELECT code FROM table WHERE code = 'ABC' -> Result: 999
  2. SELECT code FROM table WHERE code = 'DEF' -> Result: DEF
  3. SELECT code FROM table WHERE code = 'XXX' -> Result: (blank)

I appreciate if anybody could help me please.

Regards,

AMR

Try this

SELECT
    f1.doc
    , COALESCE(f2.code, f1.code) code
FROM foo f1
LEFT JOIN(
    SELECT doc, code
    FROM foo
    WHERE code <> @code
) f2 ON f2.doc = f1.doc
WHERE f1.code = @code

demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM