总和值为空时SQL返回行

总和值为空时SQL返回行,sql,Sql,我有两张桌子。一个带物料清单,一个带采购订单。现在,我想显示产品的完整物料清单以及采购表中的订单总金额 **Billofmaterials** BOM_ID BOM_Prod_id BOM_item_id 1 5 11 2 5 13 3 6 11 4 6 15 5 6 20

我有两张桌子。一个带物料清单,一个带采购订单。现在,我想显示产品的完整物料清单以及采购表中的订单总金额

**Billofmaterials**
BOM_ID   BOM_Prod_id     BOM_item_id
1        5               11
2        5               13
3        6               11
4        6               15
5        6               20

示例产品id(产品id)6有3项(id 11、15和20)

现在我得到了以下SQL

SELECT 
BOM_item_id,
SUM(DISTINCT purchasing.PU_amount) as total_on_order
FROM Billofmaterials
LEFT JOIN purchasing
ON Billofmaterials.BOM_item_id= purchasing.PU_item_id
AND purchasing.PU_status != 'Received'
AND BOM_prod_id = 6
GROUP BY BOM_item_id
此查询返回以下内容:

**Query result**
BOM_item_id   total_on_order
11            750             
20            600                       
因为BOM\u item\u id 15只有一个收到的采购订单,所以它不返回值。现在我还想重新运行BOM\u item\u id 15,但总订单为0,如:

**Expected result**
BOM_item_id   total_on_order
11            750        
15            0      
20            600                       

我需要使用什么SQL特性/函数来获得预期的结果?

您可以尝试以下方法-

SELECT BOM_item_id,coalesce(total_on_order,0) as total_on_order
FROM Billofmaterials left join
(
select PU_item_id,SUM(purchasing.PU_amount) as total_on_order
from purchasing
where purchasing.PU_status != 'Received'
group by PU_item_id
) purchasing
ON Billofmaterials.BOM_item_id= purchasing.PU_item_id
where BOM_prod_id = 6
是的,非常感谢!我在末尾添加了“按BOM\u item\u id分组”以对项目进行分组。
SELECT BOM_item_id,coalesce(total_on_order,0) as total_on_order
FROM Billofmaterials left join
(
select PU_item_id,SUM(purchasing.PU_amount) as total_on_order
from purchasing
where purchasing.PU_status != 'Received'
group by PU_item_id
) purchasing
ON Billofmaterials.BOM_item_id= purchasing.PU_item_id
where BOM_prod_id = 6