0
点赞
收藏
分享

微信扫一扫

【SQL】字符串处理函数


文章目录

  • ​​修复表中的名字​​
  • ​​left(string, count)​​
  • ​​substr(string, pos, len)​​
  • ​​按日期分组销售产品​​
  • ​​group_concat​​
  • ​​患某种疾病的患者​​

修复表中的名字

【SQL】字符串处理函数_字符串


将name的首字母大写,其余字母小写

select user_id, concat(upper(left(name, 1)), lower(substr(name, 2))) as name from Users order by user_id;

left(string, count)

  • string:字符串表达式,它可以是列的名称、字符串字面值或另一个标量函数的结果,其中基础数据类型可以表示为任何字符类型(如CHAR或VARCHAR)
  • count:整数,指定从字符串表达式的起始位置返回的字符数。
  • left返回从字符串起始处指定数量的字符;left不填充字符串,如果count大于字符串中的字符数,则left返回整个字符串

效果和 substr(string, 1, len)相同

substr(string, pos, len)

  • pos:规定字符串从何处开始往后截取,为正数时则从字段开始出开始,为负数则从结尾出开始,类似于python的负数索引。1表示第1个字符,-1表示最后一个字符
  • len:要截取字符串的长度(是从1开始计数而不是0),不写默认截取到string末尾
  • substr从string的pos位置开始截取len个字符

按日期分组销售产品

【SQL】字符串处理函数_字符串_02


【SQL】字符串处理函数_sql_03

select sell_date, 
count(distinct(product)) as num_sold,
group_concat(distinct product order by product asc SEPARATOR ",") as products
from Activities
group by sell_date
order by sell_date;

group_concat

group_concat( [distinct] 要连接的字段 [order by asc/desc 排序字段] [separator ‘分隔符’] )

患某种疾病的患者

【SQL】字符串处理函数_sql_04


【SQL】字符串处理函数_字段_05

符合条件的conditions,要么以DIAB1开头,要么DIAB1前面有其他疾病和空格

select * from Patients where conditions like "DIAB1%" or conditions like "% DIAB1%";


举报

相关推荐

0 条评论