我一直在一个网站上工作,我需要从特定的开始日期到特定的结束日期按周进行迭代,并对那个范围的列求和,然后比较它并返回最大值。我正在汇总一列并尝试将最大值返回给我的 Controller 。这是我的模型代码:
简单来说,我正在尝试:
对特定周范围内的所有销售额求和,然后返回最高周的销售额。
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;
}
此代码返回“0”作为 highest_total。如果有人能启发我,我将不胜感激。
感谢所有帮助!
最佳答案
如果我理解正确的话,你可以通过这样的查询得到你需要的一切
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 演示
由于您获得了一个销售代表的值(value),因此您不必使用 JOIN
只是 Sales
的 WHERE
条件表。
现在我不是 codeigniter 方面的专家,但您的函数可能看起来像
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');
}
关于php - 使用 CodeIgniter 在每周日期范围内迭代和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17127987/