Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to left join to first row in SQL Server

How to left join two tables, selecting from second table only the first row? first match

My question is a follow up of: SQL Server: How to Join to first row I used the query suggested in that 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 inner join results. I want to get left join results. The tabel1.id in desired results should have '2' with NULL. How to do it?

like image 221
Przemyslaw Remin Avatar asked Apr 03 '15 09:04

Przemyslaw Remin


2 Answers

use row_number and left 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

OUTPUT:

id  category
1   A
2   (null)
3   X

SQLFIDDLE DEMO

like image 156
nil Avatar answered Sep 19 '22 10:09

nil


select table1.id, 
(SELECT TOP 1 category FROM table2 WHERE table2.id=table1.id ORDER BY category ASC) AS category
FROM table1
like image 29
VincentPzc Avatar answered Sep 20 '22 10:09

VincentPzc