gpt4 book ai didi

php - SQL 按日期组按产品 ID 计数记录

转载 作者:行者123 更新时间:2023-11-29 03:18:01 25 4
gpt4 key购买 nike

我正在使用 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 |
-------------------------------------------------

最佳答案

根据您的预期输出,您需要求和 item_qty 不计算 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

");

普通的 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

Demo

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

关于php - SQL 按日期组按产品 ID 计数记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51457118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com