3

特定の開始日から特定の終了日まで週単位で繰り返し、その範囲の列を合計し、それを比較して最高値を返す必要があるサイトで作業しています。列を合計して、コントローラーに最大値を返そうとしています。ここに私のモデルコードがあります:

簡単に言えば、私はしようとしています:

特定の週の範囲のすべての売上を合計し、最も高い週の売上を返します。

function get_best_week_in_range($rep_id, $start_date, $end_date)
{
    $highest_total = 0;

    $date = $start_date; 

    while($date < $end_date)
    {
        $this->db->select('u.rep_id, s.sales_quantity, sum(s.sales_quantity) as sales_quantity ');
        $this->db->join('sales as s','s.sale_rep_id = u.rep_id');

        $this->db->where('s.date >=', $start_date);
        $this->db->where('s.date <=', $end_date);

        $this->db->group_by('u.rep_id');
        $this->db->order_by('sales_quantity', 'desc');

        $query = $this->db->get('users as u');

        $row = $query->row();

        $highest_total = ($row->sales_quantity > $highest_total) ? $row->sales_quantity : $highest_total;

        $date = strtotime("+1 week", $date);
    } 

    return $highest_total;
}

このコードは、highest_total として「0」を返しています。誰かが私を啓発できるなら、私はそれを感謝します。

助けてくれてありがとう!

4

1 に答える 1

1

私があなたを正しく理解していれば、このようなクエリで必要なものをすべて取得できます

SELECT SUM(sales_quantity) weekly_total
  FROM sales 
 WHERE sale_rep_id = $rep_id
   AND date BETWEEN $start_date AND $end_date
 GROUP BY WEEK(date)
 ORDER BY weekly_total DESC
 LIMIT 1

これがSQLFiddleのデモです

1 人の営業担当者の値を取得しているため、表の条件JOINだけを使用する必要はありません。WHEREsales

今、私はコードイグナイターの専門家ではありませんが、あなたの関数は次のようになります

function get_best_week_in_range($rep_id, $start_date, $end_date) {
     $this->db->select_sum('sales_quantity', 'weekly_total')
              ->from('sales')
              ->where('sale_rep_id', $rep_id)
              ->where('date >=', $start_date)
              ->where('date <=', $end_date)
              ->group_by('WEEK(date)')
              ->order_by('weekly_total', 'DESC')
              ->limit(1);
    $query = $this->db->get();
    return $query->row('weekly_total');
}
于 2013-06-15T23:12:13.197 に答える