2015-04-03 24 views
4

如何将连接两个表,从第二个表中只选择第一行? first match如何在SQL Server中将第一行左连接

我的问题是一个跟进:我使用的查询 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”。怎么做?

+6

变化CROSS应用到OU TER APPLY – 2015-04-03 09:06:59

+3

@ t-clausen.dk为什么你的大代表人在评论中放弃了答案,而不是在答案中?然后像我这样的小代表可以将其标记为为其他用户所接受。谢谢,效果很好! – 2015-04-03 09:11:59

回答

4

使用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 

OUTPUT:

id category 
1 A 
2 (null) 
3 X 

SQLFIDDLE DEMO

+0

Nop,它不会产生预期的结果。自己检查一下。 – 2015-04-03 09:14:49

+0

我刚才看到有问题的图片,让我再次检讨它 – jfun 2015-04-03 09:15:44

+0

@PrzemyslawRemin请再次检查它,你怎么说它没有给出正确的结果,有一个错过了逗号纠正,请再次检查并给出反馈 – jfun 2015-04-03 09:21:41

3
select table1.id, 
(SELECT TOP 1 category FROM table2 WHERE table2.id=table1.id ORDER BY category ASC) AS category 
FROM table1 
+0

这一个也正常工作 – 2015-04-03 09:20:08

+2

不,这不会工作,如果类别不排序 – jfun 2015-04-03 09:24:23

+0

感谢您的评论兄弟。但在“否”之后添加“IF”根本没有任何意义;) – VincentPzc 2015-04-03 09:29:01

1
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 
+0

这个方法也实现了目标。谢谢。 – 2015-04-03 10:55:33

+0

一个神秘的解决方案,不保证获得最低ID的类别。如果表2中存在重复的类别,那么对于某些类别,这可能会返回不同数量的行 – 2015-04-03 11:04:07

+0

当您有可用整数时,加入varchar不是很好的做法 – 2015-04-03 11:44:43