How to leave joining the first row in SQL Server

How to leave a join of two tables, choosing from the second table only the first row? first match

My question is this: SQL Server: how to join the first row I used the query suggested in this thread.

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

However, with this query, I get the results of the inner join. I want to get the results of the left join. Tabel1.id in the desired results should have "2" with NULL. How to do it?

+4
source share
3 answers

use row_numberandleft 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

CONCLUSION:

id  category
1   A
2   (null)
3   X

SQLFIDDLE DEMO

+4
source
select table1.id, 
(SELECT TOP 1 category FROM table2 WHERE table2.id=table1.id ORDER BY category ASC) AS category
FROM table1
+3
source
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 
+1

All Articles