SQL Server - Select first row that meets criteria

前端 未结 4 721
你的背包
你的背包 2021-01-29 06:18

I have 2 tables that contain IDs. There will be duplicate IDs in one of the tables and I only want to return one row for each matching ID in table B. For example:

Table

4条回答
  •  不思量自难忘°
    2021-01-29 06:32

    You should use PARTITION OVER to achieve the results.

       SELECT 
            t.objectIdA,
            t.objectIdB
        FROM (
          SELECT
             a.objectIdA,
             a.objectIdB,
            rowid = ROW_NUMBER() OVER (PARTITION BY a.objectIdA ORDER BY a.objectIdB DESC)
          FROM TableA a
           INNER JOIN TableB b ON (a.objectIdA = b.objectIdA)
        ) t
        WHERE rowid <= 1
    

    Fiddle Code: http://sqlfiddle.com/#!3/a2ccd/1

提交回复
热议问题