简体   繁体   中英

oracle sql how to select specific words

This is my school work. Although the professor said 'Don't spend too much time on it' as it is said to be a brain teaser, I would like to try to solve it. However I am still way to go.


Return all the contact names, and contact title for all customers whose contact title has "Sales" as the 2nd word of the title, the following examples are in the current data:

  • Associate Sales Assistant - should be returned
  • Associate Salesmanager - should not be returned
  • Manager Sales - should be returned
  • Assistant to Sales Manager - should not be returned

enter image description here

A simplistic approach using LIKE:

SELECT * FROM Customers WHERE 
  --Sales is a word on its own i.e. preceded and followed by a space
  --or Sales is a word on its own, at the end of the title
  (ContactTitle LIKE '% Sales %' OR ContactTitle LIKE '% Sales') AND 

  --and there is only one space before the word sales
  NOT ContactTitle LIKE '% % Sales%'

This is a way:

with sampleData(col) as (
    select 'Associate Sales Assistant' from dual union all 
    select 'Associate Salesmanager' from dual union all 
    select 'Manager Sales' from dual union all 
    select 'Assistant to Sales Manager' from dual
)
select col
from sampleData
where regexp_like(col, '^[A-Za-z]+ Sales( |$)') 

How it works:

  • ^ : the beginning of the string
  • [A-Za-z] uppercase or lowercase letters; if your "words" may contains some other character, you simply have to add it in brackets; for example, if 'aa_bb' is a valid word, this part should become [A-Za-z_]
  • + one or more occurrences of the preceding part
  • Sales a space followed by 'Sales'
  • ( |$) a space or the end of the string

You can get the same result with different patterns ; I believe this one is quite clear

Combination of substr() and instr() is what I'd do. I hate using REGEXP unless there is no other way to do it.

This should get you close... You'll need a couple more where clauses I think. Another instr to find the second word and make sure it is 'Sales', and another to verify after 'Sales' it is either a space or no characters.

    WHERE substr(title_col, instr(title_col,' Sales')+1,5) = 'Sales'

Edit: after seeing the REGEXP solution from Aleksej, that does seem more readable and simpler. If you wanted to use substr and instr, you'll need more where clauses to handle the different cases

Edit2: I like the solution from Caius Jard the best. Simple and readable.

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