ОК, вот решение:
SELECT
PERIOD_DIFF(DATE_FORMAT(now(),'%Y%m'), DATE_FORMAT(membership_StartDate,'%Y%m')) -- month difference
+ (DAY(membership_StartDate) < member_dueday) -- +1 if the start date was before the due day
+ (DAY(now()) > member_dueday) -- +1 if "now" is after the due day
- 1 -- needed due to the way we are calculating our own adjustments for due day
as payment_count
from membertomships;
Вот некоторые тестовые данные, чтобы показать крайние случаи:
create table membertomships (id int auto_increment primary key, membership_startdate date, member_dueday int);
insert into membertomships values (null, '2011-05-01', 15);
insert into membertomships values (null, '2011-05-30', 15);
insert into membertomships values (null, '2011-05-01', 4);
insert into membertomships values (null, '2011-05-30', 4);
SELECT
membership_StartDate as start,
member_dueday as due,
current_date as today,
PERIOD_DIFF(DATE_FORMAT(now(),'%Y%m'), DATE_FORMAT(membership_StartDate,'%Y%m')) - 1 + (DAY(membership_StartDate) < member_dueday) + (DAY(now()) > member_dueday) as payment_count
from membertomships;
SELECT id, membership_StartDate as start_date, member_dueday as due_day, current_date as today,
PERIOD_DIFF(DATE_FORMAT(now(),'%Y%m'), DATE_FORMAT(membership_StartDate,'%Y%m')) - 1 + (DAY(membership_StartDate) < member_dueday) + (DAY(now()) > member_dueday) as payment_count
from membertomships;
+----+------------+---------+------------+---------------+
| id | start_date | due_day | today | payment_count |
+----+------------+---------+------------+---------------+
| 1 | 2011-05-01 | 15 | 2011-07-08 | 2 |
| 2 | 2011-05-30 | 15 | 2011-07-08 | 1 |
| 3 | 2011-05-01 | 4 | 2011-07-08 | 3 |
| 4 | 2011-05-30 | 4 | 2011-07-08 | 2 |
+----+------------+---------+------------+---------------+