我需要在Codeigniter中构建此查询,但我不知道如何获得SUM的结果:
SELECT
description, SUM(amount)
FROM
PAYMENT
WHERE
(date_payment between '2014-02-01 00:00:00' AND '2014-02-28 23:59:59')
GROUP BY description;
我试图用这个得到结果:
$qwer = $this->db->query("
SELECT description, SUM(amount)
FROM PAYMENT
WHERE (date_payment between '$min_date' AND '$max_date')
GROUP BY description;");
$i = 0;
foreach ($qwer->result() as $payment) {
$det_payment[$i] = array(
'description'=>$payment->description,
'amount'=>$payment->amount
);
$i++;
}
当然“$ payment-> amount”是错误的,但如果我使用SUM的别名,则该模型不起作用。
编辑:现在我可以在描述或总和之间进行选择,但我不能同时使用select和select_sum
$this->db->select('description');
//$this->db->select_sum('amount', 'amount');
$this->db->where('date_payment >=', $min_fecha);
$this->db->where('date_payment <=', $max_fecha);
$this->db->group_by("description");
$qwer = $this->db->get('PAYMENT');
答案 0 :(得分:4)
将FALSE设置为第二个参数,'select'允许编写自定义句子。
$this->db->select('description, SUM(amount) AS amount', FALSE);
$this->db->where('date_payment >=', $min_date);
$this->db->where('date_payment <=', $max_date);
$this->db->group_by("description");
$qwer = $this->db->get('PAYMENT');
答案 1 :(得分:3)
尝试这样的事情:
$query = $this->db->select_sum('amount', 'Amount');
$query = $this->db->where(...)
$query = $this->db->get('payment');
$result = $query->result();
return $result[0]->Amount;