Search code examples
mysqlsqlgreatest-n-per-group

Getting Max date from multiple table after INNER JOIN


I have the two following tables:

table 1)
ID |  HOTEL ID | NAME 
1       100      xyz 
2       101      pqr
3       102      abc
 

table 2)
ID | BOOKING ID | DEPARTURE DATE | AMOUNT
1         1       2013-04-12        100
2         1       2013-04-14        120
3         1       2013-04-9          90
4         2       2013-04-14        100
5         2       2013-04-18        150
6         3       2013-04-12        100

I want to get the following result in MySQL such that it takes the row from Table 2 with MAX DEPARTURE DATE:

ID | BOOKING ID | DEPARTURE DATE | AMOUNT
2         1       2013-04-14        120
5         2       2013-04-18        150
6         3       2013-04-12        100

Solution

  • SELECT  b.ID,
            b.BookingID,
            a.Name,
            b.departureDate,
            b.Amount
    FROM    Table1 a
            INNER JOIN Table2 b
                ON a.ID = b.BookingID
            INNER JOIN
            (
                SELECT  BookingID, MAX(DepartureDate) Max_Date
                FROM    Table2
                GROUP   BY BookingID
            ) c ON  b.BookingID = c.BookingID AND
                    b.DepartureDate = c.Max_date