I have been working on this query for a couple of time I managed to find a solution but on the exercise solution itself it says I got the correct number of results but mismatch.
This is the exercise they propose:
Assuming that no any two battles were on the same day, wreck in next battle the ships, which in the first their battle were damaged and nowhere else took part. If the following battle is absent from the database with respect to this ship, do not insert the ship into the Outcomes table.
Your query returned the correct dataset on the first (available) database, but it returned incorrect dataset on the second checking database. * Data mismatch (162)
This is the query I wrote:
insert into outcomes
select
ship, b.name, 'sunk' from
(select ship, name, date from outcomes o
inner join battles bv
on o.battle = bv.name
where result = 'damaged'
and date = (select max(date)
from outcomes os
inner join battles ba
on os.battle = ba.name
where os.ship = o.ship)
) aq cross join battles b
where b.date = ( select min(date) from battles where date > aq.date)
This is the database description:
The database of naval ships that took part in World War II is under consideration. The database has the following relations:
- Classes(class, type, country, numGuns, bore, displacement)
- Ships(name, class, launched)
- Battles(name, date)
- Outcomes(ship, battle, result)
Ships in classes are arranged to a single project. A class is normally assigned the name of the first ship in the class under consideration (head ship); otherwise, the class name does not coincide with any ship name in the database. The Classes relation includes the class name, type (bb for a battle ship, or bc for a battle cruiser), country where the ship was built, number of main guns, gun caliber (diameter of the gun barrel, in inches), and displacement (weight in tons). The Ships relation includes the ship name, its class name, and launch year. The Battles relation covers the name and date of a battle the ships participated; while the result of their participation in the battle (sunk, damaged, or unharmed - OK) is in the Outcomes relation.
Notes:
- Outcomes relation may include the ships not included in the Ships relation.
- Sunk ship can not participate in battles after that.
And here is the tables relations http://sql-ex.ru/help/select13.php#db_3