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

后端 未结 8 1816
名媛妹妹
名媛妹妹 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:29

    Try to dedupe B like this

    SELECT  A.NAME, bb.DATA1, bb.DATA2 
    FROM    A 
    JOIN    B bb
    ON      A.NAME = B.NAME
    WHERE   NOT EXISTS (SELECT  *
                        FROM    B
                        WHERE   NAME = bb.NAME
                                AND (DATA1 > bb.DATA1
                                    OR DATA1 = bb.DATA1 AND DATA2 > bb.DATA2))

    Add more OR clauses if more DATAx columns exist.

    If A contains duplicates too, simply use DISTINCT as in the OP.

提交回复
热议问题