Select the first row in a join of two tables in one statement

后端 未结 8 1844
名媛妹妹
名媛妹妹 2020-12-29 12:59

I need to select only the first row from a query that joins tables A and B. On table B exist multiple records with same name. There are not identifiers in any of the two tab

8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 13:26

    SELECT  A.NAME, bb.DATA1, bb.DATA2 
    From A Inner Join B on A.NAME = B.NAME
    WHERE B.DATA1 = (SELECT MIN(DATA1) FROM B WHERE NAME = A.NAME)
    

    This will give your desired result, providing B.DATA1 values are unique within the set relating to table A.

    If they're not unique, the only other way I know is using CROSS APPLY in MSSQL 2005 and above.

提交回复
热议问题