如何获得上周的年份记录,明年周末结束

时间:2016-01-01 13:17:11

标签: php mysql codeigniter

如何记录上周在明年结束的年份 例如,我必须得到以下四周的记录,其中第53周将于2016年结束。

week_no  week_start  -   week_end 
==================================
week-53 (2015-12-28 to 2016-01-03) 
week-52 (2015-12-21 to 2015-12-27) 
week-51 (2015-12-14 to 2015-12-20) 
week-50 (2015-12-07 to 2015-12-13) 

以下是我的查询

function getLastFourWeekUser($table=FALSE){        
    if($table==TRUE){
        $this->db->from($table);
    }
    else{
        $this->db->from('users');        
    }        
    $endDate=date('Y-m-d',  strtotime('-3 week'));        
    $dto = new DateTime();
    $year=date('Y',strtotime($endDate));
    $week=date('W',strtotime($endDate));
    $week_start = $dto->setISODate($year,$week)->format('Y-m-d');        
    $to = date("Y-m-d", strtotime(date('o')-date('W')-7));                  
    $query = $this->db->select('count(*) as count,DATE_FORMAT(created_at,"%u-%Y") as week',false)                                        
                      ->where('created_at >=',$week_start)  
                      ->where('created_at <=',$to)
                      ->group_by('week')
                      ->order_by('week')
                      ->get();
    }

我写了一个查询,它只会给我今年的记录,即2015-12-31 只要。 但是我也想要1-jan到3rd-jan的记录。 因为第53周在2016-01-03结束。

任何人都可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

试试这个:)

SELECT
DATE_FORMAT(DATE_FORMAT(STR_TO_DATE(CONCAT(DATE_FORMAT(created_at, '%x%v'), 'Monday'), '%x%v%W'), '%Y-%m-%d'), "%u-%Y") AS week,
DATE_FORMAT(STR_TO_DATE(CONCAT(DATE_FORMAT(created_at, '%x%v'), 'Monday'), '%x%v%W'), '%Y-%m-%d') AS week_start,
DATE_FORMAT(STR_TO_DATE(CONCAT(DATE_FORMAT(created_at, '%x%v'), 'Sunday'), '%x%v%W'), '%Y-%m-%d') AS week_end,
COUNT(*) as count
WHERE created_at >='$week_start' AND created_at <='$to'
GROUP BY week
ORDER BY week