membership
表
要查看成员从membership_startdate
到目前为止支付的款项(月数),并考虑到:
SELECT DATEDIFF(GREATEST(NOW(), memberToMship_DueDay), memberToMship_StartDate) AS diff
FROM membertomship
...但是当我们认为memberToMship_StartDate
是2011-07-01并且mmebership_dueday
是07时结果是06,但是错误的结果是错误的结果。
如果memberToMship_StartDate
为“2011-01-01”且截止日期为15,那么结果将近6个月(jan - jun)(根据月份的第15个月)。
我正在使用mysql
我试过这个
SELECT DATE_SUB(DATE_ADD(memberToMship_StartDate,GREATEST(NOW(), memberToMship_DueDay)), INTERVAL memberToMship_DueDay DAY ) AS diff FROM membertomships;
但它给出了错误,如
Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GREATEST(NOW(), memberToMship_DueDay)), INTERVAL memberToMship_DueDay DAYS ) AS ' at line 1
答案 0 :(得分:2)
好的,这是解决方案:
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 |
+----+------------+---------+------------+---------------+