sql - Identifying continuous stay using mysql -


can identifying continuous stay based on dates , site name. example sample below -

name    start_dt    end_dt          site        2015-01-07  2015-01-31      tss        2015-02-01  2015-02-28      tss        2015-03-01  2015-03-14      tss        2015-03-21  2015-03-31      tss        2015-04-01  2015-04-11      tss  

expected output:

name    start_dt    end_dt          site        2015-01-07  2015-03-14      tss        2015-03-21  2015-04-11      tss 

if possible assign stay id output. thanks!

the idea identify periods of adjacent stays start. can left join see if previous stay ends on day before.

then, accumulating flag on day provides grouping mechanism identifying groups of adjacent stays. information rest aggregation:

select name, site, min(start_dt), max(end_dt) (select t.*, (case when t2.site null 1 else 0 end) startflag,              (@cnt := if(@s = site, @cnt + (case when t2.site null 1 else 0 end),                          if(@s := site, 1, 1)                         )              ) grp       t left join            t t2            on t2.site = t.site ,               t2.end_dt = date_sub(t.start_dt, interval 1 day) cross join            (select @s := '', @cnt := 0) params       order site, start_dt      ) t group name, site, grp 

Comments

Popular posts from this blog

java - Suppress Jboss version details from HTTP error response -

gridview - Yii2 DataPorivider $totalSum for a column -

Sass watch command compiles .scss files before full sftp upload -