SQL Server - Select first row that meets criteria

前端 未结 4 720
你的背包
你的背包 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

    0 讨论(0)
  • 2021-01-29 06:38
    SELECT  MAX(b.ID) AS ID
           ,MAX(Value) AS Value
           ,MAX(OtherCol1) AS OtherCol1
           ,MAX(OtherCol2) AS OtherCol2
           ,MAX(OtherCol3) AS OtherCol3
    FROM TblA AS a 
    INNER JOIN TblB AS b ON a.TblBID = b.ID
    GROUP BY TblBID
    

    Table A

    Table A

    Table B

    Table B

    Table A Data

    Table A Data

    Table B Data

    Table B Data

    Query Result

    Query Result

    0 讨论(0)
  • 2021-01-29 06:46

    You can do so,by using a subselect for table a to get one entry per objectIdA group

    select b.*,a.[objectIdB]
    from b
    join 
    (select [objectIdA], max([objectIdB]) [objectIdB]
     from a group by [objectIdA]
    ) a 
    on(b.[objectIdA] = a.[objectIdA])
    

    Fiddle Demo

    Edit deom comments to get a whole row from tablea you can use a self join for tablea

    select b.*,a.*
    from b
    join a
      on(b.[objectIdA] = a.[objectIdA])
    join (select [objectIdA], max([objectIdB]) [objectIdB]
     from a group by [objectIdA]) a1 
      on(a.[objectIdA] = a1.[objectIdA] 
         and 
        a.[objectIdB] = a1.[objectIdB])
    

    Fiddle Demo 2

    0 讨论(0)
  • 2021-01-29 06:47
    ;WITH CTE
    AS (
        SELECT  B.objectIdA
               ,A.objectIdB
               ,ROW_NUMBER() OVER (PARTITION BY B.objectIdA ORDER BY A.objectIdB DESC) rn
        FROM TableA A 
        INNER JOIN TableB B ON A.objectIdA = B.objectIdA
       )
    SELECT C.objectIdA
          ,C.objectIdB
    FROM CTE 
    WHERE rn = 1
    
    0 讨论(0)
提交回复
热议问题