Consider the following two tables, named tbl_users
and tbl_actions
respectively:
user_id user_name capture_date
u123 John Smith 2016-04-01
u124 Hannah Montana 2015-10-07
u125 James Bond 2014-07-28
user_id user_alias use_date
u123 Jonathan Smith 2012-01-01
u125 Double-O Seven 2012-02-04
u125 O-O-Seven 2015-11-25
I want to join them such that I would find the "latest used" alias of each user that is before their capture date. So the expected output is:
user_id user_name capture_date latest_alias_by_then
u123 John Smith 2016-04-01 Jonathan Smith
u124 Hannah Montana 2015-10-07
u125 James Bond 2014-07-28 Double-O Seven
How do you do that efficiently in SQL? I am using Microsoft SQL Server so functions like OVER and RANK are available too.