我想要一个SQL或PHP查询,在六个月后停用一个帐户。
简单的解决方案是
Select datediff(curdate(),last_date) as diff
我进入了复杂的情况,我不得不排除星期六和星期六。周日。
我被困在将来必须记录状态= 0
的日期或日期我在这里找到的答案基于两个日期或日期范围 但我必须计算第二次约会。
答案 0 :(得分:1)
相当肯定必须有一种比这更有效的方法,但值得一试(使用NOW()作为开始日期): -
SELECT
CASE
WHEN DAYOFWEEK(NOW()) = 7
THEN
CASE
WHEN DAYOFWEEK(DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 2 DAY)) = 7
THEN DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 4 DAY)
WHEN DAYOFWEEK(DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 2 DAY)) = 1
THEN DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 3 DAY)
ELSE
DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 2 DAY)
END
WHEN DAYOFWEEK(NOW()) = 1
THEN
CASE
WHEN DAYOFWEEK(DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 1 DAY)) = 7
THEN DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 3 DAY)
WHEN DAYOFWEEK(DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 1 DAY)) = 1
THEN DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 2 DAY)
ELSE
DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 1 DAY)
END
ELSE
CASE
WHEN DAYOFWEEK(DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) DAY)) = 7
THEN DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 2 DAY)
WHEN DAYOFWEEK(DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) DAY)) = 1
THEN DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) + 1 DAY)
ELSE
DATE_ADD(DATE(NOW()), INTERVAL (160 DIV 5) * 7 + (160 % 5) DAY)
END
END
需要天数并除以5才能获得周数,并将mod除以5以获得额外天数。如果开始日期是星期六,则会增加2天,如果星期日增加1天,则会增加7倍星期加上额外天数。然后,如果结果日是星期六,则又增加2天,如果是星期日又增加1天。
或者有点奇怪的做法: -
SELECT MAX(EndDate)
FROM
(
SELECT @StartDate:=DATE_ADD(@StartDate, INTERVAL CASE WHEN DAYOFWEEK(@StartDate) = 6 THEN 3 WHEN DAYOFWEEK(@StartDate) = 7 THEN 3 WHEN DAYOFWEEK(@StartDate) = 1 THEN 2 ELSE 1 END DAY) AS EndDate
FROM
(
SELECT units.i + tens.i * 10 + hundreds.i * 100 AS daysAdd
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units,
(SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens,
(SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) hundreds
HAVING daysAdd < 160
) Sub1
CROSS JOIN
(
SELECT @aCnt:=0, @StartDate:=DATE(NOW())
) sub2
) Sub0