sql server - How can I join 3 SQL tables and return latest current date and status? -


i have 3 tables: i'm trying write sql query joins 3 tables return first , last name table a, status of 1 there no 2 logged afterwards , logdate (only want current day) table c.

tablea:

userid | firstn | lastn | ------------------------- 2324   | john   | doe   | 2034   | jane   | doe   | 2946   | mike   | blank | 

tableb:

viewid | userid |  ----------------- 2315   | 2324   |  8956   | 2034   |  6587   | 2946   |  

tablec:

viewid | logdate                 | status | ------------------------------------------- 2315   | 2017-02-14 11:03:47.000 | 1      | 2315   | 2017-02-14 10:14:47.000 | 2      | 2315   | 2017-02-14 10:00:19.000 | 1      | 

in status column of tablec, 1 means viewing , 2 means done viewing, logdate giving date , time of status.

tablea , tableb have userid column in common. tableb , tablec have viewid column in common.

a person can view document multiple times in 1 day it's possible viewid shows multiple times in 1 day different statuses want return current status 1 user has not finished viewing document on current day.

so if @ tablec, can see same user viewed document @ 2017-02-14 10:00:19.000, finished @ 2017-02-14 10:14:47.000, , viewed again @ 2017-02-14 11:03:47.000. in example, want user viewing document @ 2017-02-14 11:03:47.000 because user has not finished viewing (status did not change 2 again yet).

i hope i'm making sense in explaining i'm trying accomplish....

so, tried haven't gotten want. can't figure out how join tablea first , last name , also, stuck trying current status of 1 if user has not finished viewing. it's returning every status of 1 throughout day.

select      tblb.viewid,     tblc.logdate, tblc.status,     tblb.userid      tableb tblb inner join      tablec tblc on tblb.viewid =  tblc.viewid     logdate >= cast(current_timestamp date)     , logdate < dateadd(dd, 1, cast(current_timestamp date))     , status = 1 

assuming it's impossible have sequence of statuses (1,1,2) i.e. open same doc without closing first, need last status. can figure out users having open docs , [left] join tablea.

select ta.firstn, ta.lastn, tbc.*     (select userid, tblc.*     tableb tblb     cross apply(        select top(1) *         tablec tblc         tblb.viewid =  tblc.viewid          , logdate >= cast(current_timestamp date)          , logdate < dateadd(dd, 1, cast(current_timestamp date))        order logdate desc        ) tblc     status = 1     ) tbc  left join tablea ta on ta.userid = tbc.userid; 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -