0

问题:我的查询返回 NULL 潜在问题:子查询格式错误,仅当我要整理的某些数据在数据集中时才有效。

今天的代码示例:

 SELECT production_order
,SUM(total_working_time_h) - (SELECT SUM(total_working_time_h) FROM {$table} WHERE production_order = '$production_order' AND (station = '出货检验 | OQC' OR production_type = 'Rework')) AS total_working_time_h_edit
,SUM(no_of_defects)         AS no_of_defects_during_production
FROM {$table}
WHERE production_order = '$production_order'  

这个作品要么有“和/或”在我的数据库中记录了伟大的产品检验| OQC'”,因此这个生产订单。如果没有,除了 NULL 之外,我根本不会得到任何数据。所以我的问题出在我的子查询中,我认为:

 SELECT SUM(total_working_time_h) FROM {$table} WHERE production_order = '$production_order' AND (station = '出货检验 | OQC' OR production_type = 'Rework')

我尝试添加一个“0”以确保它在没有成功的情况下得到 0 而不是 NULL,如下所示:

(0 + SELECT SUM(total_working_time_h) FROM {$table} WHERE     production_order = '$production_order' AND (station = '出货检验 | OQC' OR     production_type = 'Rework')

格式为文本的示例数据集:

production_order    part_nr         station                            total_working_time_h 
26135               129-108816B-UL  压接 | Crimping                     1.42
26135               129-108816B     线束组装 | Harness Assembling        7.67
26135               129-108816      测试 | Testing                       0.83
26135               129-108816B     外观全检 | Appearance inspection      0.83

给出这个输出:

production_order,total_working_time_h_edit
26135, NULL

我想要这个输出:

production_order,total_working_time_h_edit
26135, 10,45

如果我的数据集包含我想要整理的工作站或我想要整理的生产类型,那么一切都可以正常工作。但是如果数据集中缺少这两个,它会返回 NULL,因为我认为是因为子查询返回 0。

我正在使用的不同数据集的示例。如果我在数据集中用绿色单元格标记了数据,它将起作用。如果没有,我会得到上面的返回 NULL。

那么如何让我的子查询不返回NULL呢?

数据

4

1 回答 1

1

设法自己解决了这个问题。

问题:子查询返回 NULL 而不是 0。

解决方案:将 COALESCE(,0) 添加到我的子查询函数 SUM() 中,如下所示:

 COALESCE(SUM(total_working_time_h),0)

通过这样做,当 SUM() 实际上想要返回 NULL 时,它返回 0 而不是 NULL。这解决了我的问题。

于 2016-09-08T05:41:06.233 回答