mysql - Find number of "active" rows each month for multiple months in one query -
i have mysql database each row containing activate , deactivate date. refers period of time when object row represents active.
activate deactivate id 2015-03-01 2015-05-10 1 2013-02-04 2014-08-23 2
i want find number of rows active @ time during each month. ex.
jan: 4 feb: 2 mar: 1 etc...
i figured out how single month, i'm struggling how 12 months in year in single query. reason in single query performance, information used , caching wouldn't make sense in scenario. here's code have month @ time. checks if activate date comes before end of month in question , deactivate date not before beginning of period in question.
select * tblname activate <= date_sub(now(), interval 1 month) , deactivate >= date_sub(now(), interval 2 month)
if has idea how change , grouping such can indefinite number of months i'd appreciate it. i'm @ loss how group.
if have table of months care about, can do:
select m.*, (select count(*) table t t.activate_date <= m.month_end , t.deactivate_date >= m.month_start ) actives months m;
if don't have such table handy, can create 1 on fly:
select m.*, (select count(*) table t t.activate_date <= m.month_end , t.deactivate_date >= m.month_start ) actives (select date('2015-01-01') month_start, date('2015-01-31') month_end union select date('2015-02-01') month_start, date('2015-02-28') month_end union select date('2015-03-01') month_start, date('2015-03-31') month_end union select date('2015-04-01') month_start, date('2015-04-30') month_end ) m;
edit:
a potentially faster way calculate cumulative sum of activations , deactivations , take maximum per month:
select year(date), month(date), max(cumes) (select d, (@s := @s + inc) cumes (select activate_date d, 1 inc table t union select deactivate_date, -1 inc table t ) t cross join (select @s := 0) param order d ) s group year(date), month(date);
Comments
Post a Comment