Right now I'm building a huge db2 query, where I'm selecting a lot of data from a lot of tables (LEFT OUTER JOIN on 10+ tables). Most of the data is nicely selected and working fine, but then most of it is pretty straightforward
But there is one table giving me a bit of a headache. If we are just looking at the sql and result when we are not selecting from this table, it would look a bit like this: (Because of the nature of the data I can't give example from my SQL)
SQL 1:
SELECT Person.Name, Date.NameOfDate, Location.City
FROM Person LEFT OUTER JOIN
Date ON Person.Id = Date.PersonId LEFT OUTER JOIN
Location ON Date.LocationId = Location.Id
WHERE Person.IsAlive = True
Result 1:
Name - NameOfDate - City
Peter - Anna - Athen
Peter - Caroline - Washington
Simone - Carl - Athen
Now I have a table (let's call it 'Comment'). This table has some extra information on the cities. There can be several rows for each city. Example:
SQL 2:
SELECT Location.City, Comment.Text, Comment.SortingId, Comment.TypeOfData
FROM Location LEFT OUTER JOIN
Comment ON Location.Id = Comment.LocationId
Result 2:
City - Text - SortingId - TypeOfData
New York - Do not read this - 1 - 777
Washington - This text is irrelevant - 1 - 555
Washington - Make sure you visit the White House - 2 - 777
Washington - On saturdays there is a market near the docks - 3 - 777
Athen - Bring translator - 1
My problem is I need to retrieve Comment.Text in SQL 1, but only the row with the lowest SortingId where TypeOfData is 777. The result should be something like this:
Name - NameOfDate - City - Text
Peter - Anna - Athen - Bring translator
Peter - Caroline - Washington - Make sure you visit the White House
Simone - Carl - Athen - Bring translator
The closest thing I have managed to make to get this data is the following:
SELECT Person.Name, Date.NameOfDate, Location.City, Comment.Text
FROM Person LEFT OUTER JOIN
Date ON Person.Id = Date.PersonId LEFT OUTER JOIN
Location ON Date.LocationId = Location.Id LEFT OUTER JOIN
(SELECT Comment.Text FROM Comment ORDER BY Comment.SortingId FETCH FIRST 1 ROWS ONLY) AS Comment ON Location.Id = Comment.LocationId
WHERE Person.IsAlive = True
But as some might have noticed, this does not give me any result. The subselect will return the New York row, then it will filter on LocationId where it will remove the New York, leaving nothing
Any other idea?
EDIT:
The Comment table does NOT have any unique ID field. You could have two rows where the only difference is the SortingId, but the same SortingId could be used in many rows e.g. SortingId could be 1 in two rows with different LocationId