/*autor 中软作业 武新宇*/
-
(续)分组语法聚合函数(多行数据按规则聚合后比聚合前小)
/*聚合函数统计指标数据*/
2.按照name进行分组 统计
select
name,
sum(age) as age_sum,
avg(age) as age_avg,
max(age) as age_max,
min(age) as age_min,
count(age) as cnt
from student_info
group by name ;
name进行分组(作用到表)
3.按照name进行分组 结果数据 进一步统计
1.having =》 where 【只能在group by 之后使用】 where 是作用到 from 之后的
select
name,
sum(age) as age_sum,
avg(age) as age_avg,
max(age) as age_max,
min(age) as age_min,
count(age) as cnt
from student_info
group by name
having
cnt >2;
进阶:按cnt小于2分组:两种方式
1having where只能在group by后使用
2子查询 (套娃 常用)
select
from(select
from)a
统计表中有多个名字重名
1distaint
select
name,
count(name) as cnt
from student_info
group by
name
having cnt >1;
-
join 多表联查
主表 从表
事实表 维度表
广义 : inner,left right full ; 狭义:7种
内连接 inner join (取公共部分)
左连接(left join) 右连接right
select
a1.*,
b1.*
from a1 left join b1
on a1.id = b1.id ;
select
a1.*,
b1.*
from a1 right join b1
on a1.id = b1.id and a1.name=b1.name ;
full outer join
以左表为主 数据是全的 右表来匹配 匹配不上就是 null
以右表为主 数据是全的 左表来匹配 匹配不上就是 null
mysql求全连接,可以先创建所有连接条件的并集,然后其他表都和这个并集进行左连接,即可得出全连接。left join + union(可去除重复数据)+ right join
两张表时:
select * from A left join B on A.id = B.id (where 条件)
union
select *
from A right join B on A.id = B.id (where条件);
5.case when 语法结构
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list] ...
[ELSE statement_list]
END
Mysql课上案例 见其他链接
总结
面试题:谈谈对join的理解 (种类,调优)
随机数字符
空字符的使用
熟练掌握指令操作使用