sql - Calculating Date Difference Within Table Between Rows [Postgresql] -


this simplified table process should same. want calculate amount of days between logins. here table set-up query.

create table tester (user_id int, login_day date);  insert tester (user_id,login_day)  values   (1,'2013-10-02'),  (1,'2013-10-05'),  (2,'2013-10-03'),  (2,'2013-10-04'),  (2,'2013-10-07'); 

to give this:

user_id; login_day      1;  "2013-10-02"      1;  "2013-10-05"      2;  "2013-10-03"      2;  "2013-10-04"      2;  "2013-10-07" 

the results table should this:

user_id; login_day; tau      1;"2013-10-02"; 2      1;"2013-10-05"; 1 --see edit      2;"2013-10-03"; 0      2;"2013-10-04"; 2       2;"2013-10-07"; 0 

where tau difference in days-1. user_id(1) logged in on 2nd , 5th. tau value 2 since 2 days between logins.

user_id(2) has value of 0 since logged in on consecutive days.

the 7th gets 0 since no time has passed. labeled -1 if it's easier.

thanks alot help. appreciated.

edit clarification. user_id(1), 2013-10-05 has tau value of 1 because haven't logged in when treating current day 7th. e.g if hasn't logged in, tau value keeps increasing. since user_id=1 last logged in on 5th, have tau value of 1, , value keep increasing 1 everyday don't log in. again-especially a_horse_with_no_name , linger quick responses , helping me clarify question

if don't mind null in results can use(sample):

select m.user_id, m.login_day, m.login_day -  (    select max(login_day)     tester s     m.user_id = s.user_id     , s.login_day < m.login_day ) - 1 daysinbetween tester m 

if want check null , assign 0 use following (sample):

select topl.user_id, topl.login_day,        coalesce(topl.daysinbetween, 0) totald   (          select m.user_id, m.login_day,             m.login_day -             (              select max(login_day)              tester s               m.user_id = s.user_id               , s.login_day < m.login_day            ) - 1 daysinbetween          tester m        ) topl order user_id,           login_day 

here query consider (sample):

select topl.user_id, topl.login_day,        case (coalesce(topl.daysinbetween, 0)) when '-1'           '0' else coalesce(topl.daysinbetween, 0) end           totald (        select m.user_id, m.login_day,           coalesce(          (            select min(login_day)            tester s             m.user_id = s.user_id             , s.login_day > m.login_day          )- m.login_day - 1, current_date - m.login_day-1)          daysinbetween        tester m        ) topl order user_id,           login_day 

Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -