sql - Joining two log tables to get the status of an account at the time it was subject to a logged event -


i trying join 2 log tables using sql server 2012, in order add status of each account @ time subject of action logged.

the first table report created logs of contact requests users (to other users) of website, based on request date (request_date) , receiver (receiver_account_id) of request. if contact request approved, approval date (approval_date) column populated well. table looks this:

    receiver_account_id    sender_account_id    request_date    approval_date     13                     19                   2012-08-10      2012-09-01     13                     21                   2013-05-15      null     17                     19                   2011-09-11      null     25                     44                   2012-11-05      2012-11-07 

the second table logs status changes of accounts:

    date        account_id        status     2011-07-10  13                free     2012-08-15  13                premium     2010-12-10  17                free     2012-05-05  17                premium     2010-01-20  25                free     2011-04-10  25                premium     2012-11-06  25                free 

i join these 2 tables, can this:

    receiver_account_id    sender_account_id    request_date    approval_date    receiver_status_when_received    receiver_status_when_approved     13                     19                   2012-08-10      2012-09-01       free                             premium       13                     21                   2013-05-15      null             premium                          null     17                     19                   2011-09-11      null             free                             null     25                     44                   2012-11-05      2012-11-07       premium                          free 

the sender's status not important @ all.

try this

;with statusperiods (     select account_id, [status], [date] statusstart,          isnull((select min(date) status_log nxt nxt.date > sl.date , nxt.account_id = sl.account_id), '2100-1-1') statusend     status_log sl )  select request.*,      statuswhenreceived.[status]  receiver_status_when_received, statuswhenapproved.[status] receiver_status_when_approved requests  inner join  statusperiods statuswhenreceived      on statuswhenreceived.receiver_account_id = requests.account_id , requests.request_date between statuswhenreceived.statusstart , statuswhenreceived.statusend left  join  statusperiods statuswhenapproved      on statuswhenapproved.receiver_account_id = requests.account_id , requests.approval_date between statuswhenapproved.statusstart , statuswhenapproved.statusend 

Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -