如何左连接到 SQL 服务器中的第一行

How to left join to first row in SQL Server

如何左连接两个 table,只从第二个 table 中选择第一行?

我的问题是跟进: SQL Server: How to Join to first row 我使用了该线程中建议的查询。

CREATE TABLE table1(
  id INT NOT NULL
);
INSERT INTO table1(id) VALUES (1);
INSERT INTO table1(id) VALUES (2);
INSERT INTO table1(id) VALUES (3);
GO

CREATE TABLE table2(
  id INT NOT NULL
, category VARCHAR(1)
);
INSERT INTO table2(id,category) VALUES (1,'A');
INSERT INTO table2(id,category) VALUES (1,'B');
INSERT INTO table2(id,category) VALUES (1,'C');
INSERT INTO table2(id,category) VALUES (3,'X');
INSERT INTO table2(id,category) VALUES (3,'Y');
GO

------------------
SELECT 
table1.* 
,FirstMatch.category
FROM table1

CROSS APPLY (
    SELECT TOP 1 
    table2.id
    ,table2.category   
    FROM table2 
    WHERE table1.id = table2.id
    ORDER BY id
    )
    AS FirstMatch

但是,通过这个查询,我得到了内连接结果。我想获得左连接结果。所需结果中的 tabel1.id 应包含带 NULL 的“2”。怎么做?

使用row_numberleft join

with cte as(

select id,
       category,
       row_number() over(partition by id order by category) rn
       from table2
)
select t.id, cte.category
from table1 t
left outer join cte 
on t.id=cte.id and cte.rn=1

输出:

id  category
1   A
2   (null)
3   X

SQLFIDDLE DEMO

select table1.id, 
(SELECT TOP 1 category FROM table2 WHERE table2.id=table1.id ORDER BY category ASC) AS category
FROM table1
SELECT    table1.id ,table2.category 
FROM table1 Left join table2
on table1.id = table2.id
where table2.category = ( select top 1 category  from table2 t where table1.id = t.id) 
OR table2.category is NULL 

根据 t-clausen.dk 的评论,这完成了工作:

CROSS APPLY 更改为 OUTER APPLY