SQL Server - 选择符合条件的第一行

时间:2014-08-14 22:34:20

标签: sql sql-server

我有2个包含ID的表。其中一个表中会有重复的ID,我只想为表B中的每个匹配ID返回一行。例如:

表A

+-----------+-----------+
| objectIdA | objectIdB |
+-----------+-----------+
|         1 |         A | 
|         1 |         B | 
|         1 |         D | 
|         5 |         F | 
+-----------+-----------+

表B

+-----------+
| objectIdA |
+-----------+
|         1 |
|         5 |
+-----------+

会回来:

+-----------+-----------+
| objectIdA | objectIdB |
+-----------+-----------+
|         1 |         D | 
|         5 |         F | 
+-----------+-----------+

我只需要表A中与表B匹配的一个条目。返回表A的哪一行并不重要。

我正在使用SQL Server。 感谢。

4 个答案:

答案 0 :(得分:2)

;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

答案 1 :(得分:1)

您可以使用表a的子选项为每个objectIdA组获取一个条目

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

编辑deom评论以从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

答案 2 :(得分:1)

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

表A

Table A

表B

Table B

表A数据

Table A Data

表B数据

Table B Data

查询结果

Query Result

答案 3 :(得分:1)

你应该使用PARTITION OVER来实现结果。

   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

小提琴代码:http://sqlfiddle.com/#!3/a2ccd/1