Items(ItemCatalogNo, ItemType, ManufacturerName, Model, Price, QtyInWarehouse)
Supplies(SupplyNo, SupplierID, DateOrdered, DateReceived, ItemCatalogNo, Amount)
对于每种商品类型和制造商,请提供所提供商品的总数。
SELECT Items.ItemCatalogNo,
Items.ItemType,
Items.ManufacturerName,
sum(Supplies.Amount) as TotalSupply
FROM Items,
Supplies
WHERE Items.ItemcatalogNo = Supplies.ItemcatalogNo
GROUP BY Items.ItemType, Items.ItemCatalogNo,Items.ManufacturerName
;
此查询仅提供所提供的ItemTypes
个元组的元组。
如果我还需要合并那些未提供的项目(在这种情况下,TotalSupply
应该显示0
或null
),该怎么办?
我应该使用UNION
吗?
答案 0 :(得分:2)
使用左连接
SELECT Items.ItemCatalogNo,
Items.ItemType,
Items.ManufacturerName,
sum(Supplies.Amount) as TotalSupply
FROM Items
Left outer join Supplies
on Items.ItemcatalogNo = Supplies.ItemcatalogNo
GROUP BY Items.ItemType, Items.ItemCatalogNo,Items.ManufacturerName;
如果对于不存在的项目,您想要零而不是null,请使用coalesce。
SELECT Items.ItemCatalogNo,
Items.ItemType,
Items.ManufacturerName,
coalesce(sum(Supplies.Amount),0) as TotalSupply
FROM Items
Left outer join Supplies
on Items.ItemcatalogNo = Supplies.ItemcatalogNo
GROUP BY Items.ItemType, Items.ItemCatalogNo,Items.ManufacturerName;
答案 1 :(得分:2)
left outer join
也会检索一行,并使用空值填充辅助表(供应)。
coalesce(first, second)
用第二个参数替换第一个参数中的空值,所以当amount为null时,它总和为0.实际上你可以有多个参数,coalesce采用最左边的非null值。
SELECT Items.ItemCatalogNo,
Items.ItemType,
Items.ManufacturerName,
sum(coalesce(Supplies.Amount,0)) as TotalSupply
FROM Items
left outer join Supplies on Items.ItemcatalogNo = Supplies.ItemcatalogNo
GROUP BY Items.ItemType, Items.ItemCatalogNo, Items.ManufacturerName
注意:在查询中使用多个表时,更喜欢使用left outer join
(或join
)通过其主键和外键链接它们,并让{检索行必须符合的实际条件的{1}}子句。这种方式更容易区分域关系和查询中的特定条件。