Sql Inner仅在存在下一个时才加入第一个记录

时间:2011-12-06 23:23:22

标签: sql sql-server-2005 tsql

这对我来说很难得到支持。我只能用第一个结果进行内连接,但是如果存在我想要获得第二个结果。

这是我的表A

ID NAME VALUE
1   A     123
2   B     456
3   C     789
4   A     456

表B

BID BNAME BVALUE
1    A     ABC
2    A     CDE
3    B     845
4    C     1234

MY SELECT SQL:

SELECT * FROM A
CROSS APPLY (
    SELECT TOP 1 * 
        FROM B

    WHERE A.Name = B.BName 

) BB

返回

1   A     123  1   A   ABC
2   B     456  3   B   845
3   C     789  4   C   1234
4   A     456  1   A   ABC

请帮助,我想要这个结果:

1   A     123  1   A   ABC
2   B     456  3   B   845
3   C     789  4   C   1234
4   A     456  2   A   CDE

我接受tmp表和任何类型的查询:(

1 个答案:

答案 0 :(得分:3)

在评论中澄清两个表总是有匹配的行。

WITH A
     AS (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY ID) AS RN
         FROM   TableA),
     B
     AS (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY BNAME ORDER BY BID) AS RN
         FROM   TableB)
SELECT A.ID,
       A.NAME,
       A.VALUE,
       B.BID,
       B.BNAME,
       B.BVALUE
FROM   A
       JOIN B
         ON A.NAME = B.BNAME
            AND A.RN = B.RN