在codeigniter查询中使用聚合函数

时间:2014-02-06 06:41:09

标签: php codeigniter postgresql

我正在尝试以codeigniter格式编写以下查询,并在聚合函数中遇到一些问题:

$stmt = "select sum(subscription_amt) as samt, bill_month, 
                sum(loan_refund_amt*no_of_loan_installment+error_amt) as lamt 
         from pf_bill_det 
         where trim(pf_number)='$pfno' 
               and fin_year='$fyear' 
               and aproved='Y' group by bill_month";
$query = $this->db->query($stmt);

此查询最终出现错误loan_refund_amt*no_of_loan_installment+error_amt is not a column。请帮我看看如何使用codeigniter查询格式编写此查询。

2 个答案:

答案 0 :(得分:2)

你为什么不试试这个

$this->db->select("COUNT(*) AS MyCount");
$this->db->from("MyTable");
$this->db->where("field", $value);
$this->db->get();

$this->db->select("SUM(field_name) AS MySum");
$this->db->from("MyTable");
$this->db->where("field", $value);
$this->db->get();

$this->db->select("SUM(field_name) AS MySum, username, password");
$this->db->from("MyTable");
$this->db->where("field", $value);
$this->db->get();

<强> BUT

在简单查询功能中,您可以使用

$query = $this->db->query("SELECT COUNT(field_name) AS total_names, fname");

$query->result(); \\ Returns an array of objects

$query->result_array(); \\ Returns result as a pure array

$query->row(); \\ Returns a single result and first row

答案 1 :(得分:0)

试试这个,

$query=$this->db->query("select sum(subscription_amt) as samt,bill_month,sum(`loan_refund_amt`*`no_of_loan_installment`+`error_amt`) as lamt from pf_bill_det where trim(pf_number)='$pfno' and fin_year='$fyear' and aproved='Y' group by bill_month");