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

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

    If you can add to a temp table and then query from that, you can do it in one go.

    WITH T AS (temp table select), RN AS (select min row-numbers from T) SELECT T.NAME, T.DATA1, T.DATA2 FROM T INNER JOIN RN on T.row_number = RN.row_number
    

    There are many other ways to write this, but that's how I've been doing similar things.

    0 讨论(0)
  • 2020-12-29 13:49

    The tag of this question indicates that it would be a solution for DB2, but this is very similar to MS-SQL server, if so try these solutions:

    Using CROSS, it will be possible to display what exists only in both tables

    select A.*, B.DATA1, B.DATA2
    from A
    cross apply (select top 1 * from B where B.name = A.name) B
    

    But it is possible to change to OUTER to display what exists in A without the obligation to exist in B

    select A.*, B.DATA1, B.DATA2
    from A
    OUTER apply (select top 1 * from B where B.name = A.name) B
    

    In the structure of the apply statement, it would also be possible to include an ORDER statement, since there is no indication of the order of exits in table B

    0 讨论(0)
提交回复
热议问题