1. if函数:if else的效果
select if(2<1,'大','小');结果:小。
select if(2>1,'大','小')d;结果:大。
2. case when then 统计去重数据
格式:
case 要判断的字段或表达式
when 常量1 then 要显示的值1或语句1;
when 常量2 then 要显示的值2或语句2;
……
else 要显示的值n或语句n;
end
--case函数:等于
select name,area,
case area
when 新疆 then score+10
when 西藏 then score+15
else score
end as newscore
from table;
--判断,统计
count(case when dd.limit_date is not null and to_char(RES.END_TIME_,'yyyy-MM-dd') < dd.limit_date then 1 end ) as _num
--DISTINCT 去重(根据某字段)
count(DISTINCT case when dd.limit_date is not null and to_char(limit_date,'yyyy-MM-dd') < sysdate then RES.PROC_INST_ID_ end )as overNotEndCount
3、 UNION 和 UNION ALL 操作符
UNION 操作符用于合并两个或多个 SELECT 语句的结果集。
UNION 内部的 SELECT 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 SELECT 语句中的列的顺序必须相同。
--SQL UNION 语法
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
--UNION ALL 语法
--UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
4、 字符函数
--1. upper——返回大写的字符串、lower——返回小写的字符串。
select upper('tom');
select lower('TOM');
--2. concat,拼接字符串。
select concat('lastname','firstname') from name;
select name,age concat(name,'-',age) from students;
--3. substr/substring,截取函数
select substr('我爱中国',2);结果:爱中国
select substr('我爱中国',1,3);结果:我爱中
--4. instr 返回子串第一次出现的索引,如果找不到返回0
select instr('我爱数据分析','数');结果:3.
--5. replace 替换
select replace('张无忌爱上了周芷若','周芷若','赵敏');结果:张无忌爱上了赵敏。
5、 数学函数
--1、round 四舍五入
select round(1.55);select round(1.567,2);
6、 日期函数
--1、round 四舍五入
select now();返回当前系统日期+时间。
select curdate();返回当前系统日期,不包含时间。
select curtime();返回当前时间,不包含日期。
可以获取指定的部分,年、月、日、时、分、秒等:select year(now());
str_to_date 将字符通过指定的格式转换成日期
select str_to_date('1998-2-3','%Y-%c-%d');
date_format 将日期转换成字符
select date_format(now(),'%y年%m月%d日');结果:20年12月20日。
7、 案例梳理
--1、简单的分组查询:查询每个工种的最高工资
select max(score),subject from table group by subject;
--2、查询数学学科的平均分
select avg(score),subject from table where subject=math group by subject;
--3、查询员工个数>2的部门
select count(*),id from table group by id having count(*)>2;
Copyright © 2021-2022 云邦微享 | 网站备案号:粤ICP备2021113309号
文章评论