I have the following query to get the monthly amount of users:
SELECT count(user_id) from subs
where (started_at between @start_date and @start_date + interval 1 month
or (expires_at>@start_date + interval 1 month and started_at<@start_date))
If we had the following DB:
user_id started_at expires_at
=============================
1 2015-01-01 2015-12-31
2 2015-01-01 2015-01-03
3 2015-02-01 2015-02-28
4 2015-03-01 2015-03-31
5 2015-04-01 2015-04-31
6 2015-04-01 2016-04-01
7 2015-05-01 2015-05-09
I need a query that will return the following table:
2015-01 - 2
2015-02 - 2 (because one of Jan records doesn't expire till Dec)
2015-03 - 2
2015-04 - 3
2015-05 - 3
etc
So what is the efficient way to get this result in one query?