简体   繁体   中英

Return most recent row if column value matches from another column

Lets say I have a column called UserID and a table called Active Users and then one called User History .

I know I can take the most recent user history

select userid, field1, field2 
from us_hi 
where (userid,timestamp) 
    IN (select userid, max (timestamp) 
        from userhistory  
        group by userid) 
order by userid

but how would I do that if I only want to view the active users by using the userid from the active users table?

The subselect get all the users in history table that are also present in active user table, after that you join the sub select with the main query and this should give you the result you're looking for

SELECT USR.userid,field1, field2 
FROM userhistory USR
INNER JOIN (SELECT UH.userid, max (UH.timestamp) timestamp
            FROM userhistory UH
            INNER JOIN ActiveUsers AU ON AU.UserId = UH.UserId
            GROUP BY UH.userid) TMP ON TMP.userid = USR.userId AND USR.timestamp = UH.timestamp
ORDER BY USR.userid

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