简体   繁体   中英

Left join table with max value and other column from second table

I have two tables with structure similar to this:

table1
ID |Field1|Field2

table2
ID|Table1_ID|Date|Notice

I need to left join these tables in MS Access SQL based on max date from second table, but also to include 'Notice' field in new table, so result should be like this:

ID|Field1|Field2|Max_Date|Notice

I can join tables based on max date like this:

SELECT t1.ID, t1.Field1, t1.Field2, t2.Max_date
FROM table1 AS t1
LEFT JOIN
[SELECT Table1_ID, MAX(Date) AS Max_date 
FROM table2
GROUP BY Table1_ID] AS t2
ON t1.ID = t2.Table1_ID

How can I include 'Notice' field in this query too?

JOIN again:

SELECT t1.ID, t1.Field1, t1.Field2, t2m.Max_date, t2.Notice
FROM (table1 AS t1 LEFT JOIN
      (SELECT Table1_ID, MAX(Date) AS Max_date 
       FROM table2
       GROUP BY Table1_ID
      ) AS t2m
      ON t1.ID = t2m.Table1_ID
     ) LEFT JOIN
     table2 as t2
     ON t2.Table1_ID = t2m.Table1_ID AND t2.Date = t2m.Max_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