Join to only the “latest” record with t-sql

前端 未结 7 915
你的背包
你的背包 2020-12-08 08:28

I\'ve got two tables. Table \"B\" has a one to many relationship with Table \"A\", which means that there will be many records in table \"B\" for one record in table \"A\".<

7条回答
  •  生来不讨喜
    2020-12-08 08:56

    With ABDateMap AS (
        SELECT Max(RowDate) AS LastDate, TableAID FROM TableB GROUP BY TableAID
    ),
    LatestBRow As (
        SELECT MAX(ID) AS ID, TableAID FROM ABDateMap INNER JOIN TableB ON b.TableAID=a.ID AND b.RowDate = LastDate GROUP BY TableAID
    )
    SELECT columns
    FROM TableA a
    INNER JOIN LatestBRow m ON m.TableAID=a.ID
    INNER JOIN TableB b on b.ID = m.ID
    

提交回复
热议问题