1. 程式人生 > >sql經典筆試題

sql經典筆試題

詳見此處

 

表結構

1.自行新增測試資料

2.查詢平均成績大於60分的同學的學號和平均成績;

SELECT
	t1.sid 學生編號,
	AVG( t2.number ) 平均分 
FROM
	student t1
	LEFT JOIN score t2 ON t1.sid = t2.student_id 
GROUP BY
	t1.sid 
HAVING
	AVG( t2.number ) > 60

 

3.查詢所有同學的學號、姓名、選課數、總成績;

SELECT
	t1.sid "編號",
	t1.sname "姓名",
	t2.temp1 "選課數",
	t2.temp2 "總分"
FROM
	student t1,
	( SELECT student_id, COUNT( sid ) temp1, SUM( number ) temp2 FROM score GROUP BY student_id ) t2
WHERE
	t1.sid = t2.student_id;

4.查詢姓“馬”的老師的個數;

SELECT
	COUNT( tid ) 
FROM
	teacher 
WHERE
	tname LIKE "馬%"

5.查詢沒學過“馬雲”老師課的同學的學號、姓名;

SELECT DISTINCT
	t4.*
FROM
	teacher t1
	JOIN course t2 ON t1.`tid` = t2.`teacher_id` 
	JOIN score t3 on t3.course_id = t2.cid 
	JOIN student t4 on t4.sid = t3.student_id 
WHERE
	t1.tname != '馬化騰'

 

SELECT
	t1.`sid`,
	t1.`sname` 
FROM
	student t1 
WHERE
	t1.`sid` NOT IN (
SELECT
	student_id 
FROM
	score 
WHERE
	course_id IN (
SELECT
	t2.cid 
FROM
	teacher t1
	LEFT JOIN course t2 ON t1.`tid` = t2.`teacher_id` 
WHERE
	t1.tname = '馬雲' 
ORDER BY
	t2.`cid` 
	) 
	);

6.查詢學過“001”並且也學過編號“002”課程的同學的學號、姓名;

SELECT
	t1.sid,
	t1.sname 
FROM
	(
SELECT
	t1.`student_id` sid,
	t2.`sname` sname 
FROM
	score t1
	LEFT JOIN student t2 ON t1.`student_id` = t2.`sid` 
WHERE
	course_id = 1 UNION ALL
SELECT
	t1.`student_id`,
	t2.`sname` 
FROM
	score t1
	LEFT JOIN student t2 ON t1.`student_id` = t2.`sid` 
WHERE
	course_id = 2 
	) t1 
GROUP BY
	t1.sid 
HAVING
	COUNT( * ) > 1;

 子句

SELECT
	t1.`student_id` sid,
	t2.`sname` sname 
FROM
	score t1
	LEFT JOIN student t2 ON t1.`student_id` = t2.`sid` 
WHERE
	course_id = 1 UNION ALL
SELECT
	t1.`student_id`,
	t2.`sname` 
FROM
	score t1
	LEFT JOIN student t2 ON t1.`student_id` = t2.`sid` 
WHERE
	course_id = 2 

 

7.查詢課程編號“002”的成績比課程編號“001”課程低的所有同學的學號、姓名;

SELECT
	t3.`sid`,
	t3.`sname` 
FROM
	( SELECT student_id, number FROM score WHERE course_id = 2 ) t1,
	( SELECT student_id, number FROM score WHERE course_id = 1 ) t2,
	student t3 
WHERE
	t1.student_id = t3.sid 
	AND t2.student_id = t3.sid 
	AND t1.number > t2.number;

8.查詢有課程成績小於60分的同學的學號、姓名;

SELECT DISTINCT
	t1.sid "學號",
	t1.sname "姓名" 
FROM
	student t1
	LEFT JOIN score t2 ON t2.student_id = t1.sid 
WHERE
	t2.number < 60;

9.查詢沒有學全所有課的同學的學號、姓名;

SELECT
	sid,
	sname 
FROM
	student 
WHERE
	sid NOT IN 
	( 
		SELECT student_id FROM score GROUP BY student_id
		HAVING count( course_id ) = 
			( SELECT count( cid ) FROM course ) 
	)

10.查詢至少有一門課與學號為“001”的同學所學相同的同學的學號和姓名;

SELECT DISTINCT
	t1.student_id,
	t2.sname 
FROM
	score t1
	LEFT JOIN student t2 ON t1.student_id = t2.sid 
WHERE
	course_id IN ( SELECT course_id FROM score WHERE student_id = 2 )

 

待續、、、