Русский    English

Exercise #39 page 3

Solution 3.4.3

It's said but true, the following query was accepted by the system until the last days: 

  1. SELECT s.name
  2. FROM Ships s JOIN
  3. Outcomes o ON s.name = o.ship JOIN
  4. Battles b ON o.battle = b.name
  5. GROUP BY s.name
  6. HAVING COUNT(s.name) = 2 AND
  7. (MIN(result) = 'damaged' OR
  8. MAX(result) = 'damaged'
  9. )
  10. UNION
  11. SELECT o.ship
  12. FROM Classes c JOIN
  13. Outcomes o ON c.class = o.ship JOIN
  14. Battles b ON o.battle = b.name
  15. WHERE o.ship NOT IN (SELECT name
  16. FROM Ships
  17. )
  18. GROUP BY o.ship
  19. HAVING COUNT(o.ship) = 2 AND
  20. (MIN(result) = 'damaged' OR
  21. MAX(result) = 'damaged'
  22. );

Firstly, the queries, which perform joining the ships taken part in battles (Outcomes table) with the Ships table and Classes table accordingly, are being united. By the way, the predicate  

  1. o.ship NOT IN (SELECT name FROM Ships)
in the second query is apparently unwanted, because UNION will exclude all possible duplicates.

These joins are not just surplus, they are wrong, as the description of the database says that in the Outcomes table can be ships that are absent from Ships table. That is, if not the leading ship is found, which is absent from the Ships table and which satisfies the task terms, then it will not get into the resulting set of the aforecited query.

Secondly, the predicate

  1. HAVING COUNT (o.ship) = 2
confines possible variants with only two ship battles. And why can't the ship take part in more than two battles? It was not obligatory sunk after it had been damaged. And he could participate in battles and before damage (for example, with result "ok"). Then, if in the following and the last battle of a ship she has been damaged, the query 3.4.3 will deduce this ship though it and does not respond conditions of the task.

Thirdly, I don't quite understand the condition: 

  1. (MIN(result) = 'damaged' OR MAX(result) = 'damaged')

Bookmark and Share
Pages 1 2 3 4
aggregate functions Airport ALL AND AS keyword ASCII AVG Battles Bezhaev Bismarck C.J.Date calculated columns Cartesian product CASE cast CHAR CHARINDEX Chebykin check constraint classes COALESCE common table expressions comparison predicates Computer firm CONSTRAINT CONVERT correlated subqueries COUNT CROSS APPLY CTE data type conversion data types database schema DATEADD DATEDIFF DATENAME DATEPART DATETIME date_time functions DDL DEFAULT DEFAULT VALUES DELETE DISTINCT DML duplicates edge equi-join EXCEPT exercise (-2) More tags
The book was updated
month ago
©SQL-EX,2008 [Evolution] [Feedback] [About] [Links] [Team]
All right reserved.