简体   繁体   English

SQL:修改内部联接以选择一行

[英]SQL: Modifying Inner Join to Select One Row

I have two tables, A and B that I want to inner join on location . 我有两个表AB ,我想在location上进行内部联接。 However, for each row in A , there are many rows in B whose location matches. 然而,对于每行A ,有很多行B ,其location相匹配。 I want to end up with at most the same number of rows as in A . 我想最多得到与A相同的行数。 Specifically, I want to take the row in B where date is earliest. 具体来说,我想在Bdate最早的那一行。 Here's what I have so far: 这是我到目前为止的内容:

SELECT * 
FROM A 
INNER JOIN B ON A.location = B.location

How would I modify this so that each row in A only gets joined with a single row in B (using the earliest date )? 我将如何修改它,以使A中的每一行仅与B一行(使用最早的date )连接在一起?

Attempt: 尝试:

SELECT * 
FROM A 
INNER JOIN B ON A.location = B.location 
             AND B.date = (SELECT MIN(date) FROM B)

Is that the right approach? 那是正确的方法吗?

You can use the ANSI/ISO standard row_number() function: 您可以使用ANSI / ISO标准的row_number()函数:

SELECT *
FROM A INNER JOIN
     (SELECT B.*, ROW_NUMBER() OVER (PARTITION BY B.location ORDER BY B.date) as seqnum
      FROM B
     ) B
     ON A.location = B.location AND seqnum = 1;

SELECT TOP(1)*从A.LOCATION = B.LOCATION的内联接B按B.DATE排序

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM