createview v1 as selectyear,semester,title,a.id i_id,d.name i_name,b.id s_id,c.name s_name from takes a join teaches b using(course_id,sec_id,year,semester) join student c on(a.id = c.id) join instructor d on (b.id = d.id) join course using(course_id)
update instructor set salary = casewhen salary *1.1> (selectavg(salary) from instructor) then (selectavg(salary) from instructor) else salary *1.1 end where dept_name ='Comp. Sci.' and salary < (selectavg(salary) from instructor);
查询常用函数
avg() :求平均值 distinct : 去重 max() : 求最大值 min() : 求最小值 sum() : 求和 count() : 求记录的行数 count(*) : 包括null count(字段) : 该字段中不为null 的行数 groupby 字段 : 按字段分组 orderby 字段,字段 : 按字段排序,desc 降序,默认为升序 unionall 合并不去重 //窗口函数 //排序rank(),dense_rank(),row_number() // row_number 不存在并列,不会有相同的数字 //dense_rank 存在并列,不会跳数字 //rank() 存在并列,会出现数字的中断 select id,score,row_number() over (orderby score desc) as row_number, dense_rank() over (orderby score desc) as dense_rank1, rank() over (orderby score desc) as rank1 from scores // over : 在什么条件之上 partitionby 字段 : 按字段划分
id
score
row_number1
dense_rank1
rank1
01
99
1
1
1
03
99
2
1
1
02
88
3
2
3
例题:使用标量子查询,查询各院开设课程修课人数最多的前三门课程
with ta as (select dept_name,course_id,title,count (distinct id) cnt from course naturaljoin takes groupby dept_name,course_id,title), tb as( select dept_name,course_id,title,cnt,rank() over(partition by dept_name orderby cnt desc) rk from ta) select*from tb where rk<=3; //不使用窗口函数 with ta as (select dept_name,course_id,title,count(distinct id) cnt from course naturaljoin takes groupby dept_name,course_id,title), tb as (select dept_name,course_id,title,cnt, (selectcount(*)+1from ta b where a.dept_name = b.dept_name and b.cnt > a.cnt) rk from ta a) select*from tb where rk <=3orderby dept_name,rk
select id, name //同学 from student a //不存在 wherenotexists( //这样一门课程 select1from takes b //这门课程82402选了,但她没选 where id='82402'andnotexists( select1from takes c where a.id=c.id and b.course_id=c.course_id) );