Section
fefectsQty
线2 | 100 | |
---|---|---|
Table1:pections |
线1 | |
---|---|
PDR_DATE
1 | 2 | 2023-12-1016:25:46 | |
---|---|---|---|
2 | 2 | 2023-12-1016:25:47 | 50 |
Table3:production_gate |
PG_DATE
public function fetch_data($limit, $start)
{
$today = date('Y-m-d');
$this->db->select('sections.sec_name, SUM(production_defects_report.pdr_qty) as defect_qty, SUM(production_gate.pg_qty) as production_qty');
$this->db->from('production_defects_report');
$this->db->join('sections', 'sections.sec_id = production_defects_report.pdr_section_id');
$this->db->join('production_gate', 'production_gate.pg_sec_id = production_defects_report.pdr_section_id ', 'left');
$this->db->where('date(production_defects_report.pdr_date)',$today);
$this->db->where('date(production_gate.pg_date)',$today);
$this->db->group_by('sections.sec_id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row) {
$data[] = $row;
}
return $data;
}
return false;
}
您可以使用CodeIgniter的get_compiled_select()
方法构建分组和求和,并将其注入父询问。 这将使您可以将被过滤的行与仅包含当前日期的记录相关联。 1 | 2 | 2023-12-1016:25:46 | |
---|---|---|---|
2 | 2 | 2023-12-1016:25:47 | 200 |
我已经使用CodeIgniter3创建了一个模型方法,但是我发现分组的总数被错误计算 - 它们过于计算。 问题似乎是总结笛卡尔产品的结果。换句话说,加入条款导致符合条件的行在组中重复,而总和()值是无法使用的。 | 您的编码尝试似乎表明您只想获取与今天的日期至少与一行相关的部分(由于您的加入和条款)。来自Production_gate的行连接是可选的(因为您的左连接)。 |
result()
public function getSectionTotalsForToday(): array
{
$subDefects = $this->db
->select('pdr_section_id, SUM(pdr_qty) AS defect_qty')
->from('production_defects_report')
->where('DATE(pdr_date) = CURRENT_DATE', null, false)
->group_by('pdr_section_id')
->get_compiled_select();
$subProduction = $this->db
->select('pg_sec_id, SUM(pg_qty) AS production_qty')
->from('production_gate')
->where('DATE(pg_date) = CURRENT_DATE', null, false)
->group_by('pg_sec_id')
->get_compiled_select();
return $this->db
->select('s.sec_name AS Section, COALESCE(pdr.defect_qty, 0) AS defect_qty, COALESCE(pg.production_qty, 0) AS production_qty')
->from('sections s')
->join("($subDefects) pdr", 's.sec_id = pdr.pdr_section_id')
->join("($subProduction) pg", 's.sec_id = pg.pg_sec_id', 'left')
->get()
->result();
}
我认为,当您加入桌子时,您会乘行乘,因此与2个表一起加入会使行太多以无法正确总和。
您可以使用效率较低的方式,但是可以使用子问题来计算每列的方法。不要忘记到约会的位置。
SELECT
sec_name AS 'Section',
(SELECT COALESCE(SUM(pdr_qty), 0) FROM production_defects_report AS pdr WHERE pdr.pdr_section_id = s.sec_id) AS 'Defects QTY',
(SELECT COALESCE(SUM(pg_qty), 0) FROM production_gate AS pg WHERE pg.pg_sec_id = s.sec_id) AS 'Production QTY'
FROM
sections s;