Get the result of SUM and group field from Active

2020-03-31 06:27发布

问题:

I need to build this query in Codeigniter but I don't know how to get the result of the 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;

I'm trying to get the result with this:

$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++;
}

Of course "$payment->amount" is wrong, but if I use an alias for the SUM, the model doesn't work.

EDIT: Right now I can choose between the description or the sum, but I can't use both select and 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');

回答1:

Setting FALSE as second parameter, 'select' allows to write a custom sentence.

$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');

Documentation for CI2
Documentation for CI3



回答2:

try something like this:

$query = $this->db->select_sum('amount', 'Amount');
$query = $this->db->where(...)
$query = $this->db->get('payment');
$result = $query->result();

return $result[0]->Amount;