1. 程式人生 > >搞定SQL面試(3)

搞定SQL面試(3)

tinc 分數 null 排列 des name logs cname mage

  • 38、查詢各個課程及相應的選修人數;
select sc.cid,c.cname,count(distinct sid) as ‘stuCount‘ from sc sc,course c
where sc.cid=c.cid
group by sc.cid,c.cname;
  • 39、查詢不同課程但成績相同的學生的學號、課程號、學生成績;
select distinct sc1.sid,sc1.cid,sc1.score from sc sc1,sc sc2
where sc1.cid!=sc2.cid and sc1.score=sc2.score
order by sc1.score asc;
  • 40、查詢每門課程成績最好的前兩名;
select sc.cid,c.cname,sc.sid,s.sname,sc.score from student s,sc sc,course c
where s.sid=sc.sid and sc.cid=c.cid and sc.score in
(
    select sc2.score from sc sc2
    where sc2.cid=sc.cid
    order by sc2.score desc limit 2
)
order by sc.cid;
  • 41、統計每門課程的學生選修人數(超過10人的課程才統計)。
    要求輸出課程號和選修人數,查詢結果按人數降序排列,若人數相同,按課程號升序排列
select sc.Cid,COUNT(distinct Sid) as ‘StuCount‘ from SC sc
group by sc.Cid
having COUNT(distinct Sid)>=10
order by StuCount desc,sc.Cid asc
  • 42、檢索至少選修兩門課程的學生學號;
select distinct sc.sid from sc sc
group by sc.sid
having count(sc.cid)>=2;
  • 43、查詢全部學生都選修的課程的課程號和課程名;
select sc.cid,c.cname from sc sc,course c
where sc.cid=c.cid
group by sc.cid,c.cname
having count(sc.sid)=(select count(distinct s.sid) from student s)
  • 44、查詢沒學過“葉平”老師講授的任一門課程的學生姓名;
select s.sname from student s where s.sid not in
(
    select sc.sid from sc sc,course c,teacher t
    where sc.cid=c.cid and c.tid=t.tid and t.tname=‘葉平‘
)
  • 45、查詢兩門以上不及格課程的同學的學號及其平均成績
select sc.sid,avg(ifnull(sc.score,0)) as ‘AvgScore‘ from sc sc
where sc.sid in 
(select sc2.sid from sc sc2
where sc2.score<60
group by sc2.sid
having count(sc2.cid)>2
)
group by sc.sid;
  • 46、檢索“004”課程分數小於60,按分數降序排列的同學學號;(很簡單的一題)
select sc.Sid from SC sc
where sc.Cid=‘004‘ and sc.Score<60
order by sc.Score desc

文章轉載自 https://www.cnblogs.com/edisonchou/p/3878135.html
歡迎加入數據分析交流群(加群備註博客園)
技術分享圖片

搞定SQL面試(3)