简体   繁体   English

Codeigniter查询,用于选择多列总和,每行的条件为

[英]Codeigniter query for selecting sum of multiple columns with where conditions on each row

I have made this function to get sum of population percent based on group_id as 1,2 and 3 but its not working 我已经使此函数获取基于group_id为1,2和3的人口百分比的总和,但是它不起作用

public function ethnicity($value='')
        {
            $this->db->select('SUM(population_percent) as p1 where group_id=1,SUM(population_percent) as p2 where group_id=2,SUM(population_percent) as p3 where group_id=3', FALSE);
            $this->db->from('ethnic_group');
            $data=$this->db->get()->row_array();
                return $data;
        }

When you use $this->db->select() you are writing the 'select' part of a query. 当使用$this->db->select()您正在编写查询的“选择”部分。 To write the 'where' you should use $this->db->where('group_id=3') . 要编写“ where”,应使用$this->db->where('group_id=3')

In case you want to write an entire query and tell CodeIgniter to run it, you can use $this->db->query($sql) with $sql beign the actual query you want to run as seen in the documentation here . 如果要编写整个查询并告诉CodeIgniter运行它,可以将$this->db->query($sql)$sql beign一起使用要运行的实际查询,如此处的文档所示

So I think it should look something like this: 所以我认为它应该看起来像这样:

 $sql = 'your query here';
 $data = $this->db->query($sql)->row_array();
 return $data;

You need to use IF or CASE when need to do sum with this type of condition 当需要对这种类型的条件sum时,需要使用IFCASE

Use this query 使用此查询

public function ethnicity($value='')
{
    $sql = "SELECT  
              SUM(CASE WHEN group_id='1' THEN population_percent ELSE 0 END) p1,
              SUM(CASE WHEN Type='2' THEN population_percent ELSE 0 END) p2,
              SUM(CASE WHEN Type='3' THEN population_percent ELSE 0 END) p3,
            FROM ethnic_group LIMIT 1";


    $data = $this->db->query($sql)->row_array();
    return $data;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM