简体   繁体   English

在codeigniter mysql中的选择查询中使用多个IF条件查找sum()

[英]find sum() using multiple IF condition in select query in codeigniter mysql

I have a table containing details of a sale.here is my table: 我有一张包含销售详情的表。这是我的表:

    =============================================================

    id      product_name    net_price   quantity    tax_id
    =============================================================
    1       Pen             50          1               2

    2       Pencil          50          2               2       

    3       Book            100         1               3

    4       Table           10          1               3

    5       Box             50          3               2           

    6       Monitor         200         1               3

    7       Laptop          200         1               2

    8       Mouse           300         1               3

My task is to write a query such that I have to find the total sum of (net_price*quantity) for a particular ID.that is 我的任务是编写一个查询,以便我必须找到特定ID的总和(net_price*quantity)

 SUM(net_price*quantity) if tax_id==2 

AND

SUM(net_price*quantity) if tax_id==3 

Is it possible to achieve this by writing a single select query with IF ? 是否可以通过使用IF编写单个选择查询来实现? At present I am finding this in a messy way.. Can anyone help me with this? 目前,我正以一种混乱的方式找到它。有人可以帮助我吗? I am using Codeigniter MySql. 我正在使用Codeigniter MySql。

Edit 1 编辑1

In my question I have given only a part of my problem. 在我的问题中,我只给出了部分问题。 Here I am giving my actual problem and the ways I tried to sort it out. 在这里,我给出了我的实际问题以及尝试解决该问题的方法。

I have 2 tables: sales and sale_items . 我有2个表: salessale_items Table sale contains details about a sale and sale_items contains details about the products which have been saled. 表销售包含有关销售的详细信息,而销售项目包含有关已销售产品的详细信息。 For an entry in sale table there would be one or more entry in sale_items table. 对于sale表中的一项, sale_items表中将有一个或多个条目。 id in sale table and sale_id in sale_items table match for a particular sale. sale表中的idsale_id表中的sale_items匹配特定的销售。 And my task is to generate a report in excel sheet. 我的任务是在Excel工作表中生成报告。

Each product in sale_items table for a particular sale, has a tax applied. 特定销售的sale_items表中的每个产品都需要缴税。 That is In a sale, one product may have a tax@5% and another product with tax@14.5%. 也就是说,在销售中,一种产品的税率为5%,而另一种产品的税率为14.5%。 tax applied for a product is identified using tax_id . 使用tax_id标识应用于产品的tax_id In the excel sheet I have fields: sale@5%, output@5%, sale@14.5%, output@14.5% 在Excel工作表中,我有以下字段: sale@5%, output@5%, sale@14.5%, output@14.5%

sale is calculated as: sale=net_price*quantity and output=item_tax Here I am trying to fill these columns. sale的计算公式为: sale=net_price*quantityoutput=item_tax在这里,我试图填充这些列。 Here is my code I have tried so far: 到目前为止,这是我尝试过的代码:

table sales 表销售

    ===============================
    id     cust_id     total_price      
    ===============================
    1       1           1000        

    2       2           1500

table sale_items 桌子sale_items

    ==========================================================================================
    id     sales_id     cust_id     product     quantity    net_price   item_tax    tax_id
    ==========================================================================================
    1       2           2           pen             2       1000        200         3

    2       2           2           pencil          3       1500        250         2   

    3       2           2           book            2       2000        200         3

    4       2           2           Box             2       1500        150         2

table tax_rates 表tax_rates

    =======================
    tax_id     tax_rate         
    =======================
    2            tax@5%                 

    3            tax@14.5%     

Code

        function testexcel($pdf = NULL, $xls = NULL)
        {

        $dateTmp = "DATE_FORMAT(".$this->db->dbprefix('sales').".date,'%m/%Y')";
        $condition = "if(".$this->db->dbprefix('sales').".biller_id = 5, 'A', if(".$this->db->dbprefix('sales').".biller_id = 6, 'B',if(".$this->db->dbprefix('sales').".biller_id = 7,'C','D'  )))";       

        if ($pdf || $xls) {
        $this->db
        ->select("date, ".$this->db->dbprefix('warehouses').".name, 
        CONCAT(".$this->db->dbprefix('warehouses').".name,'-',".$dateTmp.",'-', ".$condition.",".$this->db->dbprefix('sales').".invoice_no) as month," ." biller, customer,
        scan_no,unit_price,if(tax_rate_id=2,item_tax,0) as taxId1,if(tax_rate_id=4,item_tax,0) as taxId2 ,
        tin,cin,cst,total_discount, item_tax, shipping,subtotal,payment_status,sales.id as saleid,total_items,total,biller_id,tax_rate_id,grand_total", FALSE)
        ->from('sales')
        ->join('sale_items', 'sale_items.sale_id=sales.id', 'left')
        ->join('companies','companies.id=sales.customer_id', 'left')
        ->join('warehouses', 'warehouses.id=sales.warehouse_id', 'left')
        ->group_by('sales.id')
        ->order_by('sales.date desc');

        $q = $this->db->get();

        if ($q->num_rows() > 0) {
        foreach (($q->result()) as $row) {
        $data[] = $row;
        }
        } else {
        $data = NULL;
        }
        if (!empty($data)) 
        {
        $this->load->library('excel');
        $this->excel->setActiveSheetIndex(0);
        $this->excel->getActiveSheet()->setTitle(lang('sales_report'));
        $this->excel->getActiveSheet()->SetCellValue('A1', lang('date'));
        $this->excel->getActiveSheet()->SetCellValue('B1', lang('branch'));

        $this->excel->getActiveSheet()->SetCellValue('C1', lang('invoice_no'));
        $this->excel->getActiveSheet()->SetCellValue('D1', lang('biller'));

        $this->excel->getActiveSheet()->SetCellValue('E1', lang('customer'));
        $this->excel->getActiveSheet()->SetCellValue('F1', lang('tin'));
        $this->excel->getActiveSheet()->SetCellValue('G1', lang('cin'));
        $this->excel->getActiveSheet()->SetCellValue('H1', lang('cst'));

        $this->excel->getActiveSheet()->SetCellValue('I1', lang('scan_no'));
        $this->excel->getActiveSheet()->SetCellValue('J1', lang('product_qty'));
        $this->excel->getActiveSheet()->SetCellValue('K1', lang('quantity'));
        $this->excel->getActiveSheet()->SetCellValue('L1', lang('prod_price'));
        $this->excel->getActiveSheet()->SetCellValue('M1', lang('sales_5%'));
        $this->excel->getActiveSheet()->SetCellValue('N1', lang('output_5%'));
        $this->excel->getActiveSheet()->SetCellValue('O1', lang('sales_14.5%'));
        $this->excel->getActiveSheet()->SetCellValue('P1', lang('output_14.5%'));
        $this->excel->getActiveSheet()->SetCellValue('Q1', lang('scanning_charge'));
        $this->excel->getActiveSheet()->SetCellValue('R1', lang('sales_0%'));
        $this->excel->getActiveSheet()->SetCellValue('S1', lang('discount')); 
        $this->excel->getActiveSheet()->SetCellValue('T1', lang('shipping'));
        $this->excel->getActiveSheet()->SetCellValue('U1', lang('total'));

        $row = 2;
        $total = 0;
        $paid = 0;
        $balance = 0;
        $quantity= 0;
        $prdt_price = 0;
        $sale5=0.00;
        $output5=0.00;
        $sale145=0.00;
        $output145=0.00;
        $scanning_charge=0;
        $sale0=0.00;
        $discount=0; 

        foreach ($data as $data_row) {
        $billerid=$data_row->biller_id;
        if($billerid==7)
        {
        $scanning_charge=1000;
        $discount=$data_row->total_discount;
        }
        else
        {
        $scanning_charge=0;
        $discount=0;
        }
        $saleid=$data_row->saleid;
        $total0=$data_row->total;
        $this->db->select("GROUP_CONCAT(DISTINCT  product_name) as products")
        ->from('sale_items')
        ->where('sale_id',$saleid);
        $q1 = $this->db->get();
        if ($q1->num_rows() > 0)
        {
        foreach (($q1->result()) as $row1) 
        {
        $products = $row1->products;
        }
        }
        else
        {
        $products="";
        }
        $this->db->select("tax_rate_id,net_unit_price,quantity,item_tax")
        ->from('sale_items')
        ->where('sale_id',$saleid);
        $q2 = $this->db->get();
        if ($q2->num_rows() > 0)
        {
        $sale5=0;
        foreach (($q2->result()) as $row2) /**here am finding the sale@14.5% and sale@5%***/
        {

        $netprice=$row2->net_unit_price;
        $qty=$row2->quantity;
        $taxid=$row2->tax_rate_id;     //getting the tax_id of a product

        //Based on tax_id calculating sale@% and output@%
        if($taxid==2)
        {
        $sale5+=$netprice*$qty;    /***Adding the sum to a variable ****/
        $output5+=$row2->item_tax;
        }
        else if($taxid==3)
        {
        $sale145+=$netprice*$qty;
        $output145+=$row2->item_tax;
        }
        else
        {
        $sale0=$total0;

        }
        }                       
        }
        $this->excel->getActiveSheet()->SetCellValue('A' . $row, $this->sma->hrld($data_row->date));
        $this->excel->getActiveSheet()->SetCellValue('B' . $row, $data_row->name);
        $this->excel->getActiveSheet()->SetCellValue('C' . $row, $data_row->month);
        $this->excel->getActiveSheet()->SetCellValue('D' . $row, $data_row->biller);

        $this->excel->getActiveSheet()->SetCellValue('E' . $row, $data_row->customer);
        $this->excel->getActiveSheet()->SetCellValue('F' . $row, $data_row->tin);
        $this->excel->getActiveSheet()->SetCellValue('G' . $row, $data_row->cin);
        $this->excel->getActiveSheet()->SetCellValue('H' . $row, $data_row->cst);                
        $this->excel->getActiveSheet()->SetCellValue('I' . $row, $data_row->scan_no);
        $this->excel->getActiveSheet()->SetCellValue('J' . $row, $products);
        $this->excel->getActiveSheet()->SetCellValue('K' . $row, $data_row->total_items);
        $this->excel->getActiveSheet()->SetCellValue('L' . $row, $data_row->total);
        $this->excel->getActiveSheet()->SetCellValue('M' . $row, $sale5);
        $this->excel->getActiveSheet()->SetCellValue('N' . $row, $output5);
        $this->excel->getActiveSheet()->SetCellValue('O' . $row, $sale145);
        $this->excel->getActiveSheet()->SetCellValue('P' . $row, $output145);
        $this->excel->getActiveSheet()->SetCellValue('Q' . $row, $scanning_charge);
        $this->excel->getActiveSheet()->SetCellValue('R' . $row, $sale0);
        $this->excel->getActiveSheet()->SetCellValue('S' . $row, $discount); 
        $this->excel->getActiveSheet()->SetCellValue('T' . $row, $data_row->shipping);
        $this->excel->getActiveSheet()->SetCellValue('U' . $row, $data_row->grand_total);

        $total += $data_row->subtotal;
        $paid += $data_row->item_tax;
        $row++;      
        }
        $this->excel->getActiveSheet()->getStyle("L" . $row . ":M" . $row)->getBorders()
        ->getTop()->setBorderStyle(PHPExcel_Style_Border::BORDER_MEDIUM);
        $this->excel->getActiveSheet()->SetCellValue('Q' . $row, $total);
        $this->excel->getActiveSheet()->SetCellValue('O' . $row, $paid);
        $this->excel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $this->excel->getActiveSheet()->getColumnDimension('B')->setWidth(20);

        $this->excel->getActiveSheet()->getColumnDimension('C')->setWidth(20);
        $this->excel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
        $this->excel->getActiveSheet()->getColumnDimension('E')->setWidth(15);
        $this->excel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
        $this->excel->getActiveSheet()->getColumnDimension('G')->setWidth(15);
        $this->excel->getActiveSheet()->getColumnDimension('H')->setWidth(20);

        $this->excel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $this->excel->getActiveSheet()->getColumnDimension('J')->setWidth(20);

        $this->excel->getActiveSheet()->getColumnDimension('K')->setWidth(15);

        $this->excel->getActiveSheet()->getColumnDimension('L')->setWidth(30);
        $this->excel->getActiveSheet()->getColumnDimension('M')->setWidth(30);
        $this->excel->getActiveSheet()->getColumnDimension('N')->setWidth(15);

        $this->excel->getActiveSheet()->getColumnDimension('O')->setWidth(30);
        $this->excel->getActiveSheet()->getColumnDimension('P')->setWidth(30);
        $this->excel->getActiveSheet()->getColumnDimension('Q')->setWidth(30);
        $this->excel->getActiveSheet()->getColumnDimension('R')->setWidth(30);
        $this->excel->getActiveSheet()->getColumnDimension('S')->setWidth(30);
        $this->excel->getActiveSheet()->getColumnDimension('T')->setWidth(30);
        $this->excel->getActiveSheet()->getColumnDimension('U')->setWidth(30);

        $filename = 'sales_report';
        $this->excel->getDefaultStyle()->getAlignment()->setVertical(PHPExcel_Style_Alignment::VERTICAL_CENTER);

        if ($xls) {
        $this->excel->getActiveSheet()->getStyle('E2:E' . $row)->getAlignment()->setWrapText(true);
        ob_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '.xls"');
        header('Cache-Control: max-age=0');
        ob_clean();
        $objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');
        $objWriter->save('php://output');
        exit();
        }

        }
        $this->session->set_flashdata('error', lang('nothing_found'));
        //redirect($_SERVER["HTTP_REFERER"]);

        } 
        }

but when I calculate the sale@5% and sale@14.5% i am getting weird results.. Can anyone help me..? 但是当我计算出sale @ 5%和sale@14.5%时,我得到的结果很奇怪。有人可以帮助我吗? Hope You got my question. 希望你能回答我的问题。 Am using codeigniter mysql. 我正在使用codeigniter mysql。 Thanks in advance 提前致谢

您可以在if条件中使用OR ,例如

if(tax_id = '2' OR tax_id = '3',SUM(net_price*quantity),net_price) as summation

If you want total amount one by one the use below code or if you want total amount for only id 2 and 3 then use where_in instead of where and change row_object to result_object . 如果您希望使用下面的代码一对一地汇总总额,或者如果您只希望ID 2和3汇总总额,则使用where_in而不是where并将row_object更改为result_object

    $this->db->select('SUM(net_price*quantity) as total_amount');
    $this->db->from('sale');
    $this->db->group_by('tax_id');
    $res = $this->db->get();
    if($res->num_rows() > 0)
    {
        return $res->result();
    }else{
         return false;
    }

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

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