SQL常用函数(以MySQL为例)




1、数据准备


创建一张表并插入数据:

在这里插入图片描述

以下常用函数以MySQL为例,其它数据库类似

2、聚合函数

-- 统计列非空值数量:count(col)
select count(*) from stu;      -- 3
-- 求和:sum(col)
select sum(score) from stu;    -- 271.5
-- 求平均值:avg(col)
select avg(score) from stu;    -- 90.5
-- 求最大值:max(col)
select max(age) from stu;      -- 18
-- 求最小值:min(col)
select min(score) from stu;    -- 88.5

3、字符串函数

-- 截取:substr(str,sta,len)、substring(str,sta,len)
select substr('abcde', 1, 3);       -- abc
select substring('abcde', 1, 3);    -- abc
-- 连接:concat(s1,s2,...)
select concat('ab', 'cd');          -- abcd
-- 转大写:upper(str)
select upper('abc');                -- ABC
-- 转小写:lower(str)
select lower('BBC');                -- bbc
-- 字符串长度:length(str)
select length('abc');               -- 3
-- 去掉字符串两端空格:trim(str)
select trim('  ab c ');             -- ab c
-- 替换:replace(str,sub,dst)
select replace('abcd', 'bc', 'x');     -- axd
-- 指定符号分隔连接:concat_ws(sep,s1,s2,...)
select concat_ws('&', 'abc', 'ef');    -- abc&ef

4、数学相关

-- 四舍五入:round(num,n)
select round(3.1415, 3);      -- 3.142
-- 取绝对值:abs(num)
select abs(-1);               -- 1
-- 将数值截断到指定小数位数:truncate(num,n)
select truncate(2.718, 2);    -- 2.71
-- 类型转换:cast(expr as type)
select cast('10' as int);     -- 10

5、日期函数

-- 获取当前时间:now()
select now();    -- 2023-11-13 21:47:43
-- 日期格式化:
select date_format('2023-11-12 18:51:45', '%Y%m%d');     -- 20231112
-- 日期加减:date_add(date,interval value unit)、date_sub(date,interval value unit)
select date_add('2023-11-01', interval -1 month);        -- 2023-10-01
-- 日期差(d1-d2天数):datediff(d1,d2)
select datediff('2023-10-15', '2023-11-10');    -- -26
-- 获取年、月、日、小时、分钟、秒:year()、month()、day()、...
select hour('2023-11-12 13:14:15');             -- 13
-- 字符串格式化为日期:str_to_date(str,format)
select str_to_date('2023-11-12 13:14:15', '%Y-%m-%d');   -- 2023-11-12

6、条件函数

-- 返回第一个非空值:coalesce(v1,v2,...)
select coalesce(null, false, '');    -- 0
-- 如果expr不为空则返回expr结果,否则返回默认值:ifnull(expr,default)
select ifnull(null, 'default');    -- default
-- 判断两个参数间的差异,如果两个入参值相同,则返回NULL,否则返回第一个入参值:nullif(expr1,expr2)
select nullif(1, null);            -- 1
-- 多条件:case when expr1 then res1 when expr2 then res2 ... else resN end
select case when score>90 then 'A' when score<=90 and score>80 then 'B' else 'C' end from stu;

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值