MySQL HIVE經典50題 21~25題

– 21、查詢不同老師所教不同課程平均分從高到低顯示

1
3個job
select distinct * from(
select t.tid,sc.cid,avg(sc.score)over(partition by t.tid,sc.cid) avg
from teacher t,course c,sc
where t.tid=c.tid and c.cid=sc.cid order by avg desc)b1
2
2個job
select t.tid,sc.cid,avg(sc.score) avg
from teacher t,course c,sc
where t.tid=c.tid and c.cid=sc.cid group by t.tid,sc.cid order by avg desc
3
2個job
select t.tid,sc.cid,avg(sc.score) avg
from teacher t join course c join sc
on t.tid=c.tid and c.cid=sc.cid group by t.tid,sc.cid order by avg desc
在這裏插入圖片描述
– 22、查詢所有課程的成績第2名到第3名的學生信息及該課程成績

1
1個job
select *
from(
select s.*,score,
dense_rank()over(partition by cid order by score desc) rank
from sc,student s
where sc.sid=s.sid)b1 where rank=2 or rank=3
在這裏插入圖片描述
– 23、統計各科成績各分數段人數:課程編號,課程名稱,[100-85],[85-70],[70-60],[0-60]及所佔百分比
60<score<70 不生效 但能執行

select c.cid,c.cname,sc.score,
case when 85<score<100 then 1
when 70<score<85 then 2
when 60<score<70 then 3
when 0<score<60 then 4
else 5 end l1
from sc,course c where sc.cid=c.cid
在這裏插入圖片描述

select c.cid,c.cname,sc.score,
case when 85<score and score<100 then 1
when 70<score and score<85 then 2
when 60<score and score<70 then 3
when 0<score and score<60 then 4
else 5 end l1
from sc,course c where sc.cid=c.cid
在這裏插入圖片描述
答案
3個job
select distinct * from(
select cid,cname,count(b1.l1)over(partition by cid,cname,l1) a,
round(count(b1.l1)over(partition by cid,cname,l1)/c,2) b
from(
select c.cid,c.cname,sc.score,
count(1)over() c,
case when 85<score and score<100 then 1
when 70<score and score<85 then 2
when 60<score and score<70 then 3
when 0<score and score<60 then 4
else 5 end l1
from sc,course c where sc.cid=c.cid
) b1
)b2
在這裏插入圖片描述

– 24、查詢學生平均成績及其名次

3個job
select *,row_number()over(order by avg desc)
from(
select sid,round(sum/max,2) avg from(
select sid,max©over() max,sum from(
select s.sid,
count(1) c,
sum(nvl(score,0)) sum
from student s left join sc on s.sid=sc.sid
group by s.sid
)b1
)b2
)b3
在這裏插入圖片描述

– 25、查詢各科成績前三名的記錄
一個job
select * from
(
select *,
row_number() over(distribute by cid sort by score desc) as rm,
rank() over(distribute by cid sort by score desc) as rk,
dense_rank() over(distribute by cid sort by score desc) as drk
from sc
) a
where a.rm < 4
;

在這裏插入圖片描述

看後續

寫SQL就像寫填空題
先把語法寫出來
select
from
where
group
然後再根據題意加條件

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章