简体   繁体   中英

SQL: Modifying Inner Join to Select One Row

I have two tables, A and B that I want to inner join on location . However, for each row in A , there are many rows in B whose location matches. I want to end up with at most the same number of rows as in A . Specifically, I want to take the row in B where date is earliest. 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 )?

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:

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排序

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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