基础
in操作符
允许我们在where 语句中规定多个值,例如我想要知道张三李四王五的成绩
select score,name from student_score_sheet
where name in ('张三','李四','王五');
原表 运行后
join 的条件写on 1 = 1代表代表什么
答案是:毫无卵用。 第一个表2行,第二个表3行。on 1=1 得到6行 实例如下
表a:
表b
select * from a join b on 1 = 1
结果如下
常见错误
where 条件写在group by 后面【应该写在前面】
distinct 和 group by 一起使用
例如
select distinct day,count(phone_number),province
from a
group by day,province
这么写不行
select day,province,count(phone_number) from (
select distinct day,province,phone_number from a )tmp1
group by day,province;
join后面语句的误用
join后面要跟括号或直接的表名,不能跟select
select a.phone_number,a.province from a
join select b.phone_number,b.name from b on a.phone_number = b.phone_number
要写括号!!!
select a.phone_number,a.province from a
join ( select b.phone_number,b.name from b ) b on a.phone_number = b.phone_number
提升技巧
计算占比
over() 函数
原表
诉求:计算这几个人的拥有的书籍的数量占比
又臭又长的代码:
select book_num/total_book_num as ratio,name from student_book_sheet a
join (select sum(book_num ) as total_book_num from student_book_sheet ) b on 1=1;
利用over()快速计算
select book_num/sum(book_num) over( ) as ratio,name from student_book_sheet;
over()分组跟group by 分组的区别
原表
感觉over()用来算占比比较合适,group by 用来算汇总 例如:
select sum(book_num),name,class from student_book_sheet2 group by name,class;
这么写相当于没有汇总
select sum(book_num),class from student_book_sheet2 group by class;
over()的效果 就相当于在每一个人那里,显示了他所在的班级的书籍总量,你看第一条张三的200,是高三一班的所有人的所有书籍的总和。
|