如何计算当前日期的最后四个星期日的日期

时间:2012-12-13 19:01:06

标签: php mysql date

我们怎样才能获得关于mysql中当前日期的最后四个星期日的日期?谢谢,

假设今天的日期为12/14/2012,那么sql查询的输出应如下所示

1st Sunday  | 2nd Sunday  |  3rd Sunday  |  4rth Sunday
11/11/2012    18/11/2012     25/11/2012     09/12/2012

更新

使用PHP我做到了:

    $date_lastsunday = strtotime("last Sunday");
$w1_sunday = $date_lastsunday - 7 * 24 * 3600;
$w2_sunday = $date_lastsunday - 14 * 24 * 3600;
$w3_sunday = $date_lastsunday - 21 * 24 * 3600;
$w4_sunday = $date_lastsunday - 28 * 24 * 3600;

想知道如何使用mysql ...

1 个答案:

答案 0 :(得分:5)

如果你想在每一行中使用它们

SELECT Curdate() - INTERVAL (Weekday(Curdate())+1) day AS `Sunday` 
UNION 
SELECT Curdate() - INTERVAL (Weekday(Curdate())+1+7*1) day 
UNION 
SELECT Curdate() - INTERVAL (Weekday(Curdate())+1+7*2) day 
UNION 
SELECT Curdate() - INTERVAL (Weekday(Curdate())+1+7*3) day 

如果您希望将它们添加到列中,请将UNION SELECT替换为,。喜欢这个

SELECT Curdate() - INTERVAL (Weekday(Curdate())+1) day `1st Sunday`, 
       Curdate() - INTERVAL (Weekday(Curdate())+1+7*1) day `2nd Sunday`, 
       Curdate() - INTERVAL (Weekday(Curdate())+1+7*2) day `3rd Sunday`, 
       Curdate() - INTERVAL (Weekday(Curdate())+1+7*3) day `4th Sunday` 

较少cpu密集方式,

SET @OFS=Weekday(Curdate())+1;
SET @CD=curdate();
sELECT @CD - INTERVAL (@OFS) day `1st Sunday`, 
       @CD - INTERVAL (@OFS+7*1) day `2nd Sunday`, 
       @CD - INTERVAL (@OFS+7*2) day `3rd Sunday`, 
       @CD - INTERVAL (@OFS+7*3) day `4th Sunday`