首页 / 博客文章 / SQL 语句实例日常梳理

数据库

SQL 语句实例日常梳理

数据库  云邦 2021-12-03 01:14:24 683 0条

1. if函数:if else的效果

  1. select if(2<1,'大','小');结果:小。
  2. select if(2>1,'大','小')d;结果:大。

2. case when then 统计去重数据
格式:
case 要判断的字段或表达式
when 常量1 then 要显示的值1或语句1;
when 常量2 then 要显示的值2或语句2;
……
else 要显示的值n或语句n;
end

  1. --case函数:等于
  2. select namearea,
  3. case area
  4. when 新疆 then score+10
  5. when 西藏 then score+15
  6. else score
  7. end as newscore
  8. from table;
  9. --判断,统计
  10. 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
  11. --DISTINCT 去重(根据某字段)
  12. 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 语句中的列的顺序必须相同。

  1. --SQL UNION 语法
  2. SELECT column_name(s) FROM table_name1
  3. UNION
  4. SELECT column_name(s) FROM table_name2
  5. --UNION ALL 语法
  6. --UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL
  7. SELECT column_name(s) FROM table_name1
  8. UNION ALL
  9. SELECT column_name(s) FROM table_name2

4、 字符函数

  1. --1. upper——返回大写的字符串、lower——返回小写的字符串。
  2. select upper('tom');
  3. select lower('TOM');
  4. --2. concat,拼接字符串。
  5. select concat('lastname','firstname') from name;
  6. select name,age concat(name,'-',age) from students;
  7. --3. substr/substring,截取函数
  8. select substr('我爱中国',2);结果:爱中国
  9. select substr('我爱中国',1,3);结果:我爱中
  10. --4. instr 返回子串第一次出现的索引,如果找不到返回0
  11. select instr('我爱数据分析','数');结果:3.
  12. --5. replace 替换
  13. select replace('张无忌爱上了周芷若','周芷若','赵敏');结果:张无忌爱上了赵敏。

5、 数学函数

  1. --1round 四舍五入
  2. select round(1.55);select round(1.567,2);

6、 日期函数

  1. --1round 四舍五入
  2. select now();返回当前系统日期+时间。
  3. select curdate();返回当前系统日期,不包含时间。
  4. select curtime();返回当前时间,不包含日期。
  5. 可以获取指定的部分,年、月、日、时、分、秒等:select year(now());
  6. str_to_date 将字符通过指定的格式转换成日期
  7. select str_to_date('1998-2-3','%Y-%c-%d');
  8. date_format 将日期转换成字符
  9. select date_format(now(),'%y年%m月%d日');结果:201220日。

7、 案例梳理

  1. --1、简单的分组查询:查询每个工种的最高工资
  2. select max(score),subject from table group by subject;
  3. --2、查询数学学科的平均分
  4. select avg(score),subject from table where subject=math group by subject;
  5. --3、查询员工个数>2的部门
  6. select count(*),id from table group by id having count(*)>2;

文章评论

置顶