2

我正在使用以下代码构建一个 Google 图表,以提取 MySQL 表中与一年中的周数相对应的所有条目。目前,周数从星期日开始,我想将其更改为从星期一开始,但我不知道该怎么做。

$i=1;
    while($i<=53)
       {
        $week_start = new DateTime();
        $week_start->setISODate(2013,$i+1);
        $date_display = $week_start->format('j M Y');

        $sessions = $wpdb->get_var($wpdb->prepare("SELECT Sum(Due) from patient_sessions WHERE Type='Session' AND Week(Date)='$i'"));

        $temp = array();

        $temp[] = array('v' => (string) $date_display); 
        $temp[] = array('v' => (string) $sessions); 
        $rows[] = array('c' => $temp);
        $i++;
    }

修订代码

$sessions = $wpdb->get_results($wpdb->prepare("SELECT Due,Date from patient_sessions WHERE Type='Session'"));
$work_times = $wpdb->get_results($wpdb->prepare("SELECT Amount,Date from work_times"));
$expenses = $wpdb->get_results($wpdb->prepare("SELECT Amount,Date from expenses WHERE Client='Psychotherapy'"));

$i=1;
while($i<=53) {
    $week_start = new DateTime();
    $week_start->setISODate(2013,$i+1);
    $date_display = $week_start->format('j M Y');

    $session_total = 0;
    $work_time_total = 0;
    $expense_total = 0;


      foreach ($sessions as $session) {
    if (date("W", strtotime($session->Date)) == $i) {
    $session_total = ($session_total+$session->Due);
    }
    }

         foreach ($work_times as $work_time) {
    if (date("W", strtotime($work_time->Date)) == $i) {
    $work_time_total = ($work_time_total+$work_time->Amount);
    }
    }

          foreach ($expenses as $expense) {
    if (date("W", strtotime($expense->Date)) == $i) {
    $expense_total = ($expense_total+$expense->Amount);
    }
          }

    $balance = ($session_total + $work_time_total - $expense_total);

    $temp = array();

    $temp[] = array('v' => (string) $date_display); 
    $temp[] = array('v' => (string) $balance); 
    $rows[] = array('c' => $temp);
    $i++;
}
4

2 回答 2

11
WEEK(date[mode]); 

date = a date value.    
mode = An integer indicating the starting of the week. 

默认参数是 0,即星期日,将其设置为 1 将是星期一,2 星期二,依此类推。

week(date,1);
于 2013-04-24T16:07:43.030 回答
0

为了让它在您的代码中工作,您应该能够将查询更改为:

"SELECT Sum(Due) FROM patient_sessions WHERE Type='Session' AND Week(Date,1)=$i"

但是,我想我可以更进一步,使用 GROUP BY 进行一次 sql 调用,然后遍历结果;

"SELECT Week(Date,1), SUM(DUE) FROM patient_sessions WHERE Type='Session' GROUP BY Week(Date,1)"

或者,您可能需要使用 WEEK(Date,2) ,具体取决于您希望如何处理跨年的周。

于 2013-04-24T16:20:20.490 回答