【SQL練習】【SQLZOO】 8 Using Null
8 Using Null
問題はこちらです。
Using Null - SQLZOO
以下が解答となります。
1.
【問題】
List the teachers who have NULL for their department.
部門にNULLがある教師を一覧化してください。
【解答】
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.
INNER JOINで、部門を持たない教師と教師を持たない部門を見逃していることに注意してください。
【解答】
そのままSubmitする
SELECT teacher.name, dept.name FROM teacher INNER JOIN dept ON teacher.dept = dept.id;
3.
【問題】
Use a different JOIN so that all teachers are listed.
すべての教師が一覧化されるよう別のJOINを使用してください。
【解答】
SELECT teacher.name, dept.name FROM teacher LEFT JOIN dept ON teacher.dept = dept.id;
4.
【問題】
Use a different JOIN so that all departments are listed.
すべての部門が一覧化されるよう別のJOINを使用してください。
【解答】
SELECT teacher.name, dept.name FROM teacher RIGHT JOIN dept ON teacher.dept = dept.id
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」を使用してください。先生の名前と携帯電話番号または「07986 4442266」を表示してください。
【解答】
SELECT name, COALESCE(mobile,'07986 444 2266') FROM teacher;
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.
COALESCE関数とLEFT JOINを使用して、教師名と部門名を出力してください。部門がない場合は、文字列「None」を使用してください。
【解答】
SELECT teacher.name, COALESCE(dept.name,'None') FROM teacher LEFT JOIN dept ON teacher.dept = dept.id;
7.
【問題】
Use COUNT to show the number of teachers and the number of mobile phones.
COUNTを使用して、教師の数と携帯電話の数を表示してください。
【解答】
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.
COUNTおよびGROUPBY dept.nameを使用して、各部門とスタッフの数を表示してください。
RIGHT JOINを使用して、エンジニアリング部門が一覧化されていることを確認してください。
【解答】
SELECT dept.name, COUNT(teacher.name) FROM teacher RIGHT JOIN dept ON teacher.dept = dept.id GROUP BY dept.name;
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 = 1 OR dept = 2 THEN 'Sci' ELSE 'Art' END FROM teacher;
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 = 1 OR dept = 2 THEN 'Sci' WHEN dept = 3 THEN 'Art' ELSE 'None' END FROM teacher;