經典SQL面試題


以下題目都在MySQL上測試可行,有疏漏或有更優化的解決方法的話歡迎大家提出,我會持續更新的:)

  1. 有三個表,如果學生缺考,那么在成績表中就不存在這個學生的這門課程成績的記錄,寫一段SQL語句,檢索出每個學生缺考的科目。
    A 學生表(student)
    字段1 學生號(s_id)
    字段2 學生名(s_name)

    B 科目表(course)
    字段1 科目號(c_id)
    字段2 科目名(c_name)

    C 成績表(grade)
    字段1 成績號(g_id)
    字段2 學生號(s_id)
    字段3 科目號(c_id)
    字段4 成績(score)

    select * from student join course left join grade on student.s_id=grade.s_id and course.c_id=grade.c_id where grade.score is null;
  2. 有如下表:
    日期(rstime) 結果(result)
    2005-05-09
    2005-05-09
    2005-05-09
    2005-05-09
    2005-05-10
    2005-05-10
    2005-05-10

    如果要生成下列結果,該如何寫sql語句?
    日期
    2005-05-09 2 2
    2005-05-10 1 2

    select rstime,sum(case result when '' then 1 else 0 end)as 勝,
    sum(case result when '' then 1 else 0 end)asfrom result group by rstime;
  3. 用一條SQL語句,查詢出成績表(grade)每門課都大於80分的學生姓名
    name course score
    張三 語文 81
    張三 數學 75
    李四 語文 76
    李四 數學 90
    王五 語文 81
    王五 數學 100
    王五 英語 90

    select distinct name from grade  where  name not in (select distinct name from grade where score<=80)


  4. 原表:
    courseid coursename score
    1 java 70
    2 oracle 90
    3 xml 40
    4 jsp 30
    5 servlet 80

    為了方便閱讀,查詢此表后的顯示結果如下(及格分數為60分):
    courseid coursename score mark
    1 java 70 pass
    2 oracle 90 pass
    3 xml 40 fail
    4 jsp 30 fail
    5 servlet 80 pass

    select *,case when score>=60 then 'pass' else 'fail' end as 'mark' from temp;

     

  5. 學生表(stu),如下:
    自動編號 學號 姓名 課程編號 課程名稱 分數
    1 2005001 張三 0001   數學 69
    2 2005002 李四 0001   數學 89
    3 2005001 張三 0001   數學 69

    刪除除了自動編號不同,其他字段都相同的學生冗余信息。
    create table temp as select 自動編號 from stu group by 學號,姓名,課程編號,課程名稱,分數;
    delete from stu where 自動編號 not in (select 自動編號 from temp);

     

  6. 學生表S,課程C,學生課程表SC,學生可以選修多門課程,一門課程可以被多個學生選修,通過SC表關聯:(SQL)
    1)寫出建表語句;
    2)寫出SQL語句,查詢選修了所有選修課程的學生;
    3)寫出SQL語句,查詢選修了至少5門以上的課程的學生。

    1、建表語句
    S表:create table s(
              id int not null primary key,
              name varchar(20)
              );
    C表:create table c(
              id int not null primary key,
              cname varchar(20)
              );
    SC表:create table sc(
              sid int not null,
              cid int not null,
              foreign key(sid) references s(id),
              foreign key(cid) references c(id)
              );

    2、寫出SQL語句,查詢選修了所有選修課程的學生
    select stu.id,stu.name from s stu where (select count(sid) from sc where sid = stu.id) = (select.count(id) from c);

    3、寫出SQL語句,查詢選修了所有選修課程的學生
    select stu.id,stu.name from s stu where (select count(sid) from sc where sid = stu.id)>=5;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM