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

前端 未结 7 911
你的背包
你的背包 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:54

    select a.*, bm.MaxRowDate
    from (
        select TableAID, max(RowDate) as MaxRowDate
        from TableB
        group by TableAID
    ) bm
    inner join TableA a on bm.TableAID = a.ID
    

    If you need more columns from TableB, do this:

    select a.*, b.* --use explicit columns rather than * here
    from (
        select TableAID, max(RowDate) as MaxRowDate
        from TableB
        group by TableAID
    ) bm
    inner join TableB b on bm.TableAID = b.TableAID
        and bm.MaxRowDate = b.RowDate
    inner join TableA a on bm.TableAID = a.ID
    

提交回复
热议问题