teacher表: iddeptnamephonemobile 101 1 Shrivell 2753 07986 555 1234 102 1 Throd 2754 07122 555 1920 103 1 Splint 2293 104 Spiregrain 3287 105 2 Cutflow ...
teacher表:
id | dept | name | phone | mobile |
---|---|---|---|---|
101 | 1 | Shrivell | 2753 | 07986 555 1234 |
102 | 1 | Throd | 2754 | 07122 555 1920 |
103 | 1 | Splint | 2293 | |
104 | Spiregrain | 3287 | ||
105 | 2 | Cutflower | 3212 | 07996 555 6574 |
106 | Deadyawn | 3345 |
dept表:
id | name |
---|---|
1 | Computing |
2 | Design |
3 | Engineering |
1.List the teachers who have NULL for their department.
select name from teacher where dept is NULL;
2.Note the INNER JOIN misses the teachers with no department and the departments with no teacher.
SELECT teacher.name, dept.name FROM teacher INNER JOIN dept ON teacher.dept=dept.id;
內部聯結INNER JOIN…ON 和之前的 JOIN…ON 是一樣的。內部聯結對NULL值不起作用。若對應的那一列有NULL值,則這些行無法對應到另一個表。只有有值的那些行能和另一表對應,才能被選擇。
所謂NULL值,就是有些行不是兩個表都有的,有些這個有,另一個沒有。
3.Use a different JOIN so that all teachers are listed.
select t.name,d.name from teacher t left join dept d on t.dept=d.id;
解題思路: left join,以teacher左表為主表,向左連接。和inner join的區別在於,inner join公共列出現null值時,將忽略null值。
4.Use a different JOIN so that all departments are listed.
select t.name,d.name from teacher t right join dept d on t.dept=d.id;
解題思路,right join,以dept右表為主表,向右連接。
Using Coalesce Fuction
5.Use COALESCE to print the mobile number. Use the number '07986 444 2266' if there is no number given. Show teacher name and mobile number or '07986 444 2266'
使用coalesce函數,顯示教師姓名和電話號碼,如果電話號碼是空值,用‘07986 444 2266’填充
select name,coalesce(mobile,'07986 444 2266') from teacher;
解題思路,colaesce函數是缺失值處理,針對的是null的情況,註意,coalesce函數對空格不起作用。
6.Use the COALESCE function and a LEFT JOIN to print the teacher name and department name. Use the string 'None' where there is no department.
select t.name,coalesce(d.name,'None') from teacher t left join dept d on t.dept=d.id;
7.Use COUNT to show the number of teachers and the number of mobile phones.
select count(name),count(mobile) from teacher;
8.Use COUNT and GROUP BY dept.name to show each department and the number of staff. Use a RIGHT JOIN to ensure that the Engineering department is listed.
select d.name,count(t.name) from teacher t right join dept d on t.dept=d.id group by 1;
9.Use CASE to show the name of each teacher followed by 'Sci' if the teacher is in dept 1 or 2 and 'Art' otherwise.
使用 CASE 顯示每位教師的姓名,如果教師在部門 1 或 2,則顯示“Sci”,否則顯示“Art”。
select name,(case when dept in(1,2) then 'Sci' else 'Art' end) from teacher;
解題思路:考察case when
10.Use CASE to show the name of each teacher followed by 'Sci' if the teacher is in dept 1 or 2, show 'Art' if the teacher's dept is 3 and 'None' otherwise.
使用 CASE 顯示每位教師的姓名,如果教師在部門 1 或 2,則顯示“Sci”,如果教師的部門是 3,則顯示“Art”,否則顯示“None”。
select name,(case when dept in(1,2) then 'Sci' when dept=3 then 'Art' else 'None' end) from teacher;
解題思路:考察case when 多個條件。