简体   繁体   中英

Join Tables Based on Correlated Subquery, SQL

I need to join two tables that are described below:

Table1:
ID  Date       Info1
1   1/29/2011     i10
1   1/30/2011     i11


Table2:
ID  Date       Info2
1    1/31/2011   i2

I would like to left join the records in Table 2 identified by ID, Month, Year to that in Table 1 identified by the same ID, Month, Year but use the last available record date as the joining record. So for example, in the data above I would join the record in Table 2 to the second record in Table 1 because they match in ID, Month, Year and record 2 of Table 1 has the greatest available day for that (ID, Month, Year) combination. The correct result is:

ID Date Info1 Info2

1 1/30/2011 i11 i2

The SQL code I am coming up with so far is pretty convoluted. Please suggest something. I am using MySQL.

[I want to] ...use the last available record date as the joining record

Solve that first, with a derived table. Assuming that ID, Date is unique, then you can easily group by ID and take the MAX date.

SELECT
   T1.*,
   T2.*
FROM Table1 as T1
JOIN (
   SELECT 
      ID, MAX(Date) as Date
   FROM Table1
   GROUP BY 
      ID
) as Last ON
   T1.ID = Last.ID
   AND T1.Date = Last.Date
LEFT OUTER JOIN Table2 as T2 ON
   T1.ID = Last.ID
   AND MONTH(T1.Date) = MONTH(T2.Date)
   AND YEAR(T1.Date) = YEAR(T2.Date)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM