Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 442
user1504606 Avatar asked Dec 01 '25 06:12

user1504606


1 Answers

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
  • SQLFiddle Demo
like image 78
John Woo Avatar answered Dec 03 '25 19:12

John Woo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!