数据分析师必备技能之SQL(6) -- 字符串函数

2020-08-20  本文已影响0人  ArnoChanszu

      文本也是数据处理中常见的类型之一,相比于相对成熟的数学函数而言,字符串的处理场景更复杂多变,熟练掌握常见的字符串函数则事半功倍。

     1. 基础字符串处理函数

    length(string A):返回字符串A的长度

    eg:select length('abced') 得到 5

   trim(string A) :去除字符串两边的空格

    eg:select trim(' abc ') 得到 'abc'

   lower(string A)/ lcase(string A):返回字符串的小写形式,常用于不确定原始字段是否统一为大小写

    eg:select lower('abCdE') 得到 abcde

   upper(string A)/ ucase(string A):返回字符串的大写形式,常用于不确定原始字段是否统一为大小写

    eg:select upper('abCdE') 得到 ABCDE

      2. 提取部分字符串

      2.1 使用substr/substring函数

     substr/substring (string A, int start):返回字符串A从start位置到结尾的字符串

    eg:select substring('abcde', 3) 得到 cde

     substring(string A, int start, int len):返回字符串A从start位置开始,长度为len的字符串

    eg:select substring('abcde', 3,2) 得到 cd

  2.2  使用regexp_extract函数(HQL支持)

     regexp_extract(string subject, string pattern, int index):将字符串subject按照pattern正则表达式的规则拆分,返回index指定的字符

    eg:select regexp_extract('abcdefg', 'a(b)(.*?)(e)',2) 得到 cd

     PS:1)如果 subject为空,或者pattern为空,或者pattern匹配不到字符串,则返回值为空

              2)index取值为 0:返回pattern匹配到的整个结果;

                index取值为1:返回pattern中第一个() 匹配到的结果;

                …

                index取值为n:返回pattern中第n个() 匹配到的结果;

                index取值小于0或者大于n:报错。

      3. 拼接字符串:使用concat/concat_ws函数

    concat(string A, string B) :返回字符串AB的拼接结果,可以多个字符串进行拼接

    eg:select concat('abc', 'def','gh') 得到abcdefgh

    concat_ws(string X, stringA, string B) 返回字符串A和B由X拼接的结果

    eg:select concat_ws(',', 'abc', 'def', 'gh') 得到 abc,def,gh

上一篇下一篇

猜你喜欢

热点阅读