简体   繁体   中英

SQL query to get row corresponding to max value with join

Here are 2 tables -

Table A

id | col1 | col2 
----------------
 1 | val1 | val2
 2 | val3 | val4 


Table B

id | version | col3 | col4
--------------------------
 1 |    1    | val5 | val6
 1 |    2    | val7 | val8

I would like to fetch the values of A.col1, A.col2, B.col3, B.col4 where A.id = B.id and B.version is the max version. Thus, I want a result set like -

id | version | col1 | col2 | col3 | col4 
----------------------------------------
 1 |   2     | val1 | val2 | val7 | val8

What SQL query can be used to achieve this result?

Thanks!

select a.id, b2.version, a.col1, a.col2, b.col3, b.col4
from a
join b on a.id=b.id
join (select id, max(version) version from b group by id) b2 on b2.id=b.id and b2.version=b.version

Similar to preceding answer, but you can actually just use one join instead of two:

Preparing Test Data:

Select * INTO #TableA 
from (
    Select 1 as ID , 'val1' as col1, 'val2' as col2
    UNION Select 2, 'val3', 'val4'
) A

Select * INTO #TableB 
from (
    Select 1 as id, 1 as version, 'val5' as col3, 'val6' as col4
    UNION Select 1, 2, 'val7', 'val8'
) B

Getting Results:

Select A.col1, A.col2, B.col3, B.col4
from #TableA A
JOIN (
    Select ID, max(version) as version, max(col3) as col3, max(col4) as col4 from #TableB Group By ID
) B ON A.ID = B.ID

Try this:

SELECT *
FROM A
INNER JOIN ( 
   SELECT * FROM B 
   INNER JOIN (
       SELECT ID, MAX(Version) 
       FROM B 
       GROUP BY ID
   ) XXX ON (B.ID = XXX.ID)
) YYY ON (A.ID = YYY.ID)

Tried this on SQL Fiddle:

select tableA.id, version, col1, col2, col3, col4 from tableA
join tableB on tableA.id = tableB.id
where version = (select max(version) from tableB where tableB.id = tableA.id);

This will give you a result set with the max versions and corresponding values for every id in Table A that exists in Table B.

SQLFiddle

According to docs Group-wise Maximum of a Certain Column you can write your query as

select a.*,
b.`col3`,
b.`col4`,
b.version
from a
join b on(a.id = b.id)
left join b b2 on(b.id = b2.id and b.version < b2.version)
where b2.id is null

Fiddle Demo

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