3

我有以下两张表一和二

ONE           TWO

ID            ID  CODE  
-----         ---------
1             1    1
2             1    2
3             2    1
4             3    1  
5             3    2  
              3    3

需要输出

ID    CODE  
----------  
1     2  
2     1  
3     3  
4     NULL  
5     NULL  

我使用了以下查询,但它抛出错误“与 JOIN 运算符或 MERGE 语句关联的 ON 子句无效。

SELECT  A.ID
       ,B.CODE
FROM   ONE A 
LEFT JOIN
       TWO B
ON     A.ID = B.ID
   AND B.CODE = (
                   SELECT 
                         MAX(Z.CODE)
                   FROM TWO Z
                   WHERE Z.ID = A.ID
            )
4

3 回答 3

4

您可以通过加入和聚合来做到这一点(如果我理解正确的逻辑):

select ONE.id, max(TWO.CODE)
from ONE left outer join
     TWO
     on ONE.id = TWO.id
group by ONE.id;
于 2013-08-26T13:14:56.533 回答
2

由于您还标记了 SQL-Server,因此您可以使用ROW_NUMBER

WITH CTE AS
(
    SELECT ONE.ID,  TWO.CODE,
        RN = ROW_NUMBER() OVER (PARTITION BY ONE.ID ORDER BY TWO.CODE DESC)
    FROM ONE LEFT OUTER JOIN TWO
        ON ONE.ID=TWO.ID
)
SELECT  ID, CODE FROM CTE WHERE RN = 1

DEMO

于 2013-08-26T13:15:00.440 回答
1
SELECT  A.ID
   ,B.CODE
FROM   ONE A 
LEFT outer JOIN
   (select id,max(code) CODE from two group by id) B
ON     A.ID = B.ID

我相信这就是你正在寻找的......

于 2013-08-26T13:26:10.050 回答