4

我有两张桌子:

       A
---------------
No.    Name
1      J.Smith
2      R.Alan
3.     D.Williams


       B
----------------------------
ID.    Date        Address    No.(FK from table A) 
1      10/03/01   blah blah   1
2      08/02/05   blah blah   2
3.     12/01/02   blah blah   3
4.     03/07/11   blah blah   1
5.     30/03/09   blah blah   2

我想将两个表连接在一起,根据表 B 中的最近日期省略具有重复名称的行。例如,如果我使用左内连接将表 A 和 B 连接在一起,我将为 J. Smith 获得两行(基于表 B) 中的第 1 行和第 4 行。我想排除日期较旧的日期(表 B 中的第 1 行)。

我怎样才能做到这一点?

编辑:

我需要包括表 B 中的所有列。

4

4 回答 4

1

也许是这样的:

;WITH CTE
AS
(
    SELECT
        ROW_NUMBER() OVER(PARTITION BY tblB.[No] ORDER BY tblB.[Date]) AS RowNbr,
        tblB.*
    FROM
        B AS tblB
)
SELECT
    *
FROM
    A AS tblA
    LEFT JOIN CTE
        ON tblA.No=CTE.No
        AND CTE.RowNbr=1
于 2012-04-17T09:17:01.423 回答
1
WITH [max_dates] AS (
    SELECT [No], MAX([Date]) AS [Date]
    FROM [TableB]
    GROUP BY [No]
)
SELECT [a].[Name], [b].[Date]
FROM [TableA] AS [a]
JOIN [max_dates] AS [b] ON ([a].[No] = [b].[No])
ORDER BY [a].[No] ASC
于 2012-04-17T09:23:14.007 回答
0
SELECT A.No 
     , A.Name
     , C.Date
     , C.Address
     , C. ...
FROM A 
LEFT JOIN
    ( SELECT Address , ... , No, Date,  ROW_NUMBER() OVER(PARTITION BY No ORDER BY Date DESC) AS row
        FROM B 
    ) C ON A.No = C.No 
WHERE C.row = 1

WHERE COALESCE(C.row, 1) = 1 [if there is no link ,and you'll get Date NULL]

编辑:如果你在 B 中有很多列

SELECT A.No 
     , A.Name
     , C.* (also row)
FROM A 
LEFT JOIN
    ( SELECT * ,  ROW_NUMBER() OVER(PARTITION BY No ORDER BY Date DESC) AS row
        FROM B 
    ) C ON A.No = C.No 
WHERE C.row = 1
于 2012-04-17T09:13:45.623 回答
0

Rory Hunter 很好地使用了 CTE,或者没有它:

 SELECT [A].Name, [B].Date
 FROM [A]
     INNER JOIN [B]
         INNER JOIN
         ( -- build a limitation on B
             SELECT No, MaxDate = Max(Date)
             FROM [B]
             GROUP BY No
         ) BLimit
            ON BLimit.No = B.No
            AND BLimit.MaxDate = B.Date
         ON B.No = A.No

BLimit 充当限制器,仅允许每个否 (FK) 的最高日期通过。并且 B 中的所有字段都可以用于查询,因为 B 上的限制仅使用 BLimit。

于 2012-04-17T11:46:29.743 回答