Iterating through results and performing sum on values
I can give you some guidance, at a minimum. I don't use MySQL in detail, but in general:

Step 1: get the date ranges

I assume that for each row returned from mytable that you want the date in that row as a start date, and the date in the following row as the end date. Check MySQL documentation on "windowing functions" (related to aggregate functions). There may be a function that can do this for you (in SQL Server, the function is LEAD. If you can't find that, you can always do a subquery in each row, returning the smallest date (matching the same criteria) bigger than the date in the current row.  This would look something like:

SELECT id, dates as startdate
      ,(SELECT MIN(dates) FROM mytable WHERE id = a.id and dates &gt; a.dates) as enddate
  FROM mytable a
 WHERE id = '123'


(Exact syntax may be different).

Step 2: Get the SUMs

Given that we have the start and end dates for each range, getting the SUM of the age ranges is fairly easy. We join the query we did above against Table2 and use GROUP BY and SUM. I assume that dates that fall on a boundary should not be included in both groups, so we'll toss them into the later group:

SELECT dtr.startdate, dtr.enddate, SUM(ag.age) as sum_Age
  FROM (SELECT id, dates as startdate
              ,(SELECT MIN(dates) FROM mytable WHERE id = a.id and dates &gt; a.dates) as enddate
          FROM mytable a
         WHERE id = '123'
       ) dtr
       LEFT OUTER JOIN Table2 as ag ON (ag.date &gt;= dtr.startdate AND ag.date &lt; dtr.enddate)
 GROUP BY dtr.startdate, dtr.enddate;


(Again, syntax may need adjusting for MySQL). Note that this does not sum up ages for any dates either before the first date, or on or after the last date, as those are not part of valid ranges.

Hope this helps point you in the right direction.