我有一个包含 Orders 的表(每个订单一条记录)和一个包含 OrderDetails 的表(每个产品一条记录)。我希望我的 SELECT 语句在以 ProductID 命名的列中返回每种产品的数量。这样,我不会为每个 ProductID 显式编写查询,而是让查询适应它在 OrderDetails 表中找到的任何 ProductID。
结果将是这样的:
OrderID TrackingNr ProductID1 ProductID2 ProductID3
1 1Zetc 6 0 2
2 1Zetc2 0 1 1
我目前有以下内容:
SELECT Orders.OrderID AS OrderID,
TrackingNumbers.TrackingNumber AS TrackingNumber,
(SELECT Quantity FROM OrderDetails WHERE Orders.OrderID = OrderDetails.OrderID AND ProductCode = 'FPIA0009') AS FPIA0009,
(SELECT Quantity FROM OrderDetails WHERE Orders.OrderID = OrderDetails.OrderID AND ProductCode = 'FPIA0030') AS FPIA0030,
((SELECT Quantity FROM OrderDetails WHERE Orders.OrderID = OrderDetails.OrderID AND ProductCode = 'FPIA0060') +
(SELECT Quantity FROM OrderDetails WHERE Orders.OrderID = OrderDetails.OrderID AND ProductCode = 'FPIA0060xP')) AS FPIA0060,
(SELECT Quantity FROM OrderDetails WHERE Orders.OrderID = OrderDetails.OrderID AND ProductCode = 'FPIA0120') AS FPIA0120
FROM Orders, TrackingNumbers WHERE Orders.OrderID = TrackingNumbers.OrderID
ORDER BY OrderID, ShipDate
您可以看到,上面我明确要求每个特定 ProductID 的数量,但还有更多,我宁愿简化。
您还可以看到,我尝试将两种不同产品的数量相加,因为它们来自同一个库存,但由于某种原因,结果始终为空。
非常感谢您的帮助!