[英]SQL count record by date group by product id
I'm using Codeigniter, I face the problem when I COUNT
total quantity FROM wo_tbl_sales_items WHERE pdate GROUP BY pid
. 我使用的是笨,我所面临的问题,当我
COUNT
总量FROM wo_tbl_sales_items WHERE pdate GROUP BY pid
。 query not given the corrected result, I show my code below, 查询未给出更正的结果,我在下面显示我的代码,
$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
);
}
}
Also I show my database table structure, 我还展示了我的数据库表结构,
----------------------------------------------------------------------------
| 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 |
----------------------------------------------------------------------------
I look result like this, please see below structure. 我看起来像这样的结果,请参见下面的结构。
-------------------------------------------------
| Items Name | Qty | Total Amount |
-------------------------------------------------
| Iphone 6s | 4 | 4000 |
| Samsung A6 | 1 | 600 |
-------------------------------------------------
According to your expected output, you need to sum
item_qty not count item_qty 根据您的预期输出,您需要将item_qty
sum
而不是item_qty
$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
");
Plain sql would look like 普通的SQL看起来像
select si.pid,
si.item_name,
ifnull(sum(`si`.`item_qty`), 0) as total_items_count,
ifnull(format(sum(`si`.`item_total`),2), '0.00') as total_items_amount
from wo_tbl_sales_items si
where si.pdate = '2018-07-21'
group by si.pid,si.item_name
order by total_items_count DESC
Try to move the formatting part (FORMAT(....)) from query to your application code. 尝试将格式部分(FORMAT(....))从查询移动到您的应用程序代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.