select only first letters of words from a varchar field

二次信任 提交于 2020-01-03 11:34:14

问题


I was asked in an interview,a question from oracle sql.this seemed to be a simple question but i had no clue to answer.could anybody help?

if there is string like "newyork is a beautiful city" in a colum.

select column_name from table_name;

will result

newyork is a beautiful city

what is the query required to give the output as a string with all the first letters. i.e., the output should be

niabc

回答1:


Provided you're not concerned with maintaining the case of the output this can be done quite simply without the need for recursion:

SQL> select
  2      translate(
  3            initcap('newyork is a BEAUTIFUL city')
  4               , 'ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz'
  5               , 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  6              )
  7  from dual
  8  /

TRANS
-----
NIABC

SQL>

If the sentence contains numerals, punctuation, etc then we would have to add those characters to the first replacement string, which could get rather tedious.




回答2:


The answer is using REGEX_SUBSTR.

See the docs here, and a close example here.




回答3:


You could use the split function described here (replacing the comma by a space), in order to split the sentence by its spaces. Then, you could use the substr function as AJ says, because the result of the split would allow you to start from char 1 to char 2 of every "piece".

It involves substr after all, right??

PS. I would rather process the result in a layer above, not during the query. But that's me.




回答4:


Maybe it would involve using the function substr?



来源:https://stackoverflow.com/questions/2174656/select-only-first-letters-of-words-from-a-varchar-field

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!