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

标签 php mysql codeigniter

我有一个包含销售详细信息的表格。这是我的表格:

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

    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

我的任务是编写一个查询,以便我必须找到特定 ID 的(net_price*quantity) 总和。即

 SUM(net_price*quantity) if tax_id==2 

并且

SUM(net_price*quantity) if tax_id==3 

是否可以通过使用 IF 编写单个选择查询来实现此目的?目前我发现这个问题很困惑。任何人都可以帮助我解决这个问题吗?我正在使用 Codeigniter MySql。

编辑 1

在我的问题中,我只给出了问题的一部分。在这里我给出我的实际问题以及我尝试解决它的方法。

我有 2 个表:salessale_items。表 sale 包含有关销售的详细信息,sale_items 包含有关已销售产品的详细信息。对于 sale 表中的一项,sale_items 表中将有一个或多个条目。 sale 表中的 idsale_items 表中的 sale_id 与特定销售相匹配。我的任务是在 Excel 工作表中生成报告。

sale_items表中针对特定销售的每件产品均需缴纳税款。也就是说,在一次销售中,一种产品的税收可能为 5%,而另一种产品的税收可能为 14.5%。使用 tax_id 识别产品所适用的税费。在 Excel 工作表中我有字段: 销售@5%,输出@5%,销售@14.5%,输出@14.5%

销售额的计算方式为:sale=net_price*quantityoutput=item_tax 在这里我试图填充这些列。这是我迄今为止尝试过的代码:

表格销售

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

    2       2           1500

表格 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

税率表

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

    3            tax@14.5%     

代码

        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"]);

        } 
        }

但是当我计算 sale@5% 和 sale@14.5% 时,我得到了奇怪的结果..任何人都可以帮助我..?希望你能明白我的问题。我正在使用 codeigniter mysql。提前致谢

最佳答案

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

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

关于php - 在 Codeigniter mysql 的选择查询中使用多个 IF 条件查找 sum(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34853186/

相关文章:

php - 比较mysql中的两个逗号分隔值

select - 使用 and 嵌套 sql 语句

PHP/MySQL - 表单输入值 "&"保存为 "&"

php - Mysql 两张表,获取没有相同值的数据

php - 从数据库中获取所有内容 - MySQL

php - 全文搜索不适用于某些表

php - 删除单个字段的验证器约束

php - 选择 PHP 缓存技术 : output caching into files vs. 操作码缓存

尝试截断表时出现 MySQL 错误

mysql - mysql 如何与进程一起工作?