SQL練習題

Yfeil發表於2024-05-10

1.查詢部門最高工資的員工資訊

表 t_employee 儲存了所有的員工資料。

id name salary department_id
1 Joe 7000.00 1
2 Henry 8000.00 2
3 Sam 6000.00 2
4 Max 9000.00 1

表 t_department 儲存了所有的部門資料。

id name
1 IT
2 Sales

寫一段SQL查詢出各部門工資最高的員工資訊。如下所示,IT部門工資最高的是Max,Sales部門工資最高的是Henry。

department employee salary
IT Max 9000.00
Sales Henry 8000.00

線上練習:查詢部門最高工資的員工資訊

檢視題解
 SELECT
	d.name AS department,
    e.name AS employee,
    s.salary AS salary
FROM
	(SELECT department_id,MAX(salary) AS salary FROM t_employee GROUP BY department_id) AS s
    LEFT JOIN t_department d ON d.id = s.department_id
    LEFT JOIN t_employee e ON e.department_id = s.department_id AND e.salary = s.salary;

2.用一條SQL語句查詢出每門課都大於80分的學生姓名

name kecheng fenshu
zhangsan yuwen 81
zhangsan shuxue 75
lisi yuwen 76
lisi shuxue 90
wangwu yuwen 81
wangwu shuxue 100
wangwu yingyu 90

線上練習:用一條SQL語句查詢出每門課都大於80分的學生姓名

檢視題解
 SELECT name FROM t GROUP BY name HAVING MIN(fenshu) > 80;

3.刪除除了id不同,其他都相同的學生冗餘資訊

id xuehao name kechengid kechengname fenshu
1 2005001 zhangsan 0001 shuxue 69
2 2005002 lisi 0001 shuxue 89
3 2005001 zhangsan 0001 shuxue 69
檢視題解
 DELETE FROM t WHERE id NOT IN (SELECT MIN(id) FROM t GROUP BY xuehao,name,kechengid,kechengname,fenshu);

4.用一條sql語句顯示所有可能的比賽組合

一個叫 t 的表,裡面只有一個欄位name,一共有4條紀錄,分別是a,b,c,d,對應四個球隊,現在四個球隊進行比賽,用一條sql語句顯示所有可能的比賽組合.

name
a
b
c
d

線上練習:用一條sql語句顯示所有可能的比賽組合

檢視題解
 SELECT * FROM t a JOIN t b ON a.name > b.name;

5.表格式轉換

怎麼把這樣一個表:

year month amount
1991 1 1.1
1991 2 1.2
1991 3 1.3
1991 4 1.4
1992 1 2.1
1992 2 2.2
1992 3 2.3
1992 4 2.4

查成這樣一個結果:

year m1 m2 m3 m4
1991 1.1 1.2 1.3 1.4
1992 2.1 2.2 2.3 2.4

線上練習:表格式轉換

檢視題解
 SELECT 
	year,
    MAX(IF(month = 1, amount, NULL)) AS m1,
    MAX(IF(month = 2, amount, NULL)) AS m2,
    MAX(IF(month = 3, amount, NULL)) AS m3,
    MAX(IF(month = 4, amount, NULL)) AS m4 
FROM t 
GROUP BY year;