SQL条件/字符串函数

条件函数

  • if
    语法: if(boolean testCondition, T valueTrue, T valueFalseOrNull)
    说明: 当条件testCondition为TRUE时,返回valueTrue;否则返回valueFalseOrNull
举例:select if(app_name = 'group',object_id,null) as deal_id 
from dw.topic_order where partition_pay_date = '2016-04-22'
  • 非空查找函数: COALESCE
    语法: COALESCE(T v1, T v2, …)
    说明: 返回参数中的第一个非空值;如果所有值都为NULL,那么返回NULL
举例:select coalesce(uuid,'') as uuid from dw.topic_order
 where partition_pay_date = '2016-04-22'
  • 条件判断函数:CASE
    语法 : CASE a WHEN b THEN c [WHEN d THEN e]* [ELSE f] END
    说明:如果 a 等于 b ,那么返回 c ;如果 a 等于 d ,那么返回 e ;否则返回 f
举例:
select object_id,user_id,uuid, case when client_type like 'ip%' then 'ios' 
when client_type like 'andr%' then 'android' 
else 'other' end as utm_medium from dw.topic_order 
where partition_pay_date = '2016-04-22'

注意:相对而言,case when是最全的条件函数,可以用于判断多种条件;次之是if函数,属于二分判断;最后是coalesce函数,该函数只能对空值和非空进行判断。

字符串函数

  • 字符串长度函数:length

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

  • 字符串反转函数:reverse

语法: reverse(string A)。返回字符串A的反转结果

举例:select reverse(abcedfg’) from dual; ##返回值为gfdecba

  • 字符串连接函数:concat

语法: concat(string A, string B…)。返回输入字符串连接后的结果,支持任意个输入字符串

举例:select count(distinct if(partition_is_paid = 1,null,concat(coalesce(uuid,''),coalesce(deal_id,'')))) as order_cnt from dw.topic_order where partition_pay_date = '2016-04-22'

  • 带分隔符字符串连接函数:concat_ws

语法: concat_ws(string SEP, string A, string B…)。返回输入字符串连接后的结果,SEP表示各个字符串间的分隔符

举例:select concat_ws(',','abc','def','gh') from dual; ##返回值为abc,def,gh

  • 字符串截取函数:substr,substring

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

举例:select substr('abcde',3) from dual; ##返回值cde

  • 字符串截取函数:substr,substring

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

举例:select substr('abcde',3,2) from dual; ##返回值为cd

  • 字符串转大写函数:upper,ucase

语法: upper(string A) ucase(string A)。返回字符串A的大写格式

  • 字符串转小写函数:lower,lcase

语法: lower(string A) lcase(string A)。返回字符串A的小写格式

  • 去空格函数:trim

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

举例:select trim(' abc ') from dual; ##返回值为abc

  • 左边去空格函数:ltrim

语法: ltrim(string A)。去除字符串左边的空格

  • 右边去空格函数:rtrim

语法: rtrim(string A)。去除字符串右边的空格

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容