1

我创建了一个包含两个表的数据库:Table1Table2.

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,我怎样才能合并这两个表,以便它会给我每个帐户的最新状态?

4

1 回答 1

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
于 2012-05-22T12:02:38.227 回答