我创建了一个包含两个表的数据库:Table1
和Table2
。
Table1
包含以下数据:
Account# Account Owner
1 Person1
2 Person2
Table2
包含:
Account# Date Modified Status
1 5/15/2011 Open
2 4/15/2011 Closed
1 5/21/2011 Pending
2 6/15/2011 Cancelled
使用SQL,如何合并这两个表,以便它为我提供每个帐户的最新状态?
答案 0 :(得分:1)
这样做:
SELECT Table1.[Account#],
Table1.[Account Owner],
L.LastOfDate,
Table2.Status
FROM ((SELECT Table2.[Account#],
Max(Table2.[Date Modified]) AS LastOfDate
FROM Table2
GROUP BY Table2.[Account#]) AS L
INNER JOIN Table1
ON L.[Account#]=Table1.[Account#])
INNER JOIN Table2
ON (L.[Account#]=Table2.[Account#])
AND (L.LastOfDate=Table2.[Date Modified]);
将导致:
Account# Account Owner LastOfDate Status
1 Person1 05/21/2011 Pending
2 Person2 06/15/2011 Cancelled