按日期分组和产品ID的SQL计数记录

时间:2018-07-21 14:44:36

标签: php mysql codeigniter

我正在使用Codeigniter,当我COUNT总数量FROM wo_tbl_sales_items WHERE pdate GROUP BY pid时遇到问题。查询未给出更正的结果,我在下面显示我的代码,

$this->db->select("
        IFNULL(FORMAT(SUM(`si`.`item_total`),2), '0.00') as total_items_amount,
        IFNULL(COUNT(`si`.`item_qty`), 0) as total_items_count

    ");
    $this->db->where('si.pdate =', $date);
    $this->db->from('wo_tbl_sales_items si');
    $this->db->group_by('si.pid');
    $this->db->order_by('total_items_count', 'DESC');
    $result = $this->db->get();
    if($result->num_rows() > 0)
    {

        foreach($result->result() as $row){

           $data['parts'][] = array(
                'total_items_amount' => $row->total_items_amount,
                'total_items_count' => $row->total_items_count
            ); 
        }

    }

我还要显示我的数据库表结构,

----------------------------------------------------------------------------
| mainid |   pid  |   item_name   |  item_qty  | item_total  |    pdate    |
----------------------------------------------------------------------------
|   1    |   164  |   Iphone 6s   |     2      |   2000      |  2018-07-21 |
|   2    |   164  |   Iphone 6s   |     1      |   1000      |  2018-07-21 |
|   3    |   164  |   Iphone 6s   |     1      |   1000      |  2018-07-21 |
|   4    |   165  |   Samsung A6  |     1      |   600       |  2018-07-21 |
----------------------------------------------------------------------------

我看起来像这样的结果,请参见下面的结构。

-------------------------------------------------
|  Items Name    |    Qty   |  Total Amount     |
-------------------------------------------------
|   Iphone 6s    |     4    |      4000         |
|   Samsung A6   |     1    |       600         |
-------------------------------------------------

1 个答案:

答案 0 :(得分:0)

根据您的预期输出,您需要mysqli_insert(X,X) item_qty不计算item_qty

sum

普通sql看起来像

$this->db->select("
        IFNULL(FORMAT(SUM(`si`.`item_total`),2), '0.00') as total_items_amount,
        IFNULL(SUM(`si`.`item_qty`), 0) as total_items_count

");

Demo

尝试将格式部分(FORMAT(....))从查询移至您的应用程序代码。