Reputation: 1
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
Upvotes: 0
Views: 438
Reputation: 23
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.
Upvotes: 0
Reputation: 74605
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%'
Upvotes: 1
Reputation: 22949
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 partSales
a space followed by 'Sales'( |$)
a space or the end of the stringYou can get the same result with different patterns; I believe this one is quite clear
Upvotes: 0