2012-12-13 184 views
0

如何才能得到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 

UPDATE:

使用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做...

+2

[?你嘗試過什麼(http://www.whathaveyoutried.com/)請參閱[常見問題](HTTP: //stackoverflow.com/faq)。 –

+0

在這裏發表你的努力...你做了什麼才能得到最後四個星期天.... – guri

+0

@JohnConde我試過'選擇date_sub(curdate(),間隔7天,選擇date_sub(curdate(),間隔14天'但他們在當前日期方面不準確 –

回答

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`