- group by 一般要在select中配合聚合函数使用,否则没有意义。
SELECT id, sum(revenue) from Dep group by id;
- 聚合函数得出的结果与非聚合元素不一定对应
select
dept_no,
a.emp_no,
max(Salary) as maxSalary
from salarys a
left join dept_emp b on a.emp_no = b.emp_no
group by dept_no
- 窗口排序函数
rank()113, dense_rank()112, row_number()123, first_value, last_value, lag()前n行数据, lead()后n行数据 后加
over(order by salary range数值幅度\rows上下行范围 between unbounded preceding and unbounded following)
- 求出邮件发送异常的概率
avg(case e.type when 'no_completed' then 1 else 0 end)
- 添加指定区间日期(对应的还有date_sub()函数)
Date_add(min(date),interval 1 day)
- 查询两个班级前三名
Select * from
(Select
Name,
Class_id,
score,
rank() over(partition by class_id order by score DESC) scoreRank
from t_student) s
where s.scoreRank < 4
- 转换字段类型
cast(字段名 as 转换的类型)
- 保留三位有效数
round( ,3)
- union表示将两个select的结果连接起来
- if是一个三目表达式,用来判断查询出来的值
select
name ,
if(sex=0, '女', ‘男’) as sex
from stu;
- 分区并排序
row_number() over(partition by user_id order by date asc)
- 计算每个分区的数量
count(*) over(partition by user_id)
- SQL语句的执行顺序
首先,要清楚在select语句中都用到哪些关键词;其次,要知道执行一步就会产生一个对应的虚拟表。
(8)SELECT (9)DISTINCT<select_list>
(1)FROM <left_table>
(3)<join_type> JOIN <right_table>
(2)ON <join_condition>
(4)WHERE <where_condition>
(5)GROUP BY <group_by_list>
(6)WITH {CUBE|ROLLUP}
(7)HAVING <having_condition>
(10)ORDER BY <order_by_list>
(11)LIMIT <limit_number>