简体   繁体   English

如果列值与另一列匹配,则返回最新行

[英]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 . 假设我有一个名为UserID的列和一个名为Active Users的表,然后有一个称为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? 但是,如果我只想使用活动用户表中的userid查看活动用户,该怎么办?

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

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

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