是否可以在连接的上下文中引用内部查询的外部查询?内部查询的“where(sid.ItemID = i.itemID)”给了我一个错误。我以为我过去做过这个,所以我搜索了所有存储的过程,但显然我做了一些替换来让它工作。我怀疑我可以删除那一行并且它会起作用但是它对内部where子句更有效吗?
SELECT departmentName
, supplierName
, so.SalesOrderID
, ss.warehouseInvoiceNo
, ss.transactionNo
, ss.storeID
, s.storeName
, s.storeNo
, tr.transactionDate
, p.period
, sooos.salesOrderID
, sooos.salesOrderOutOfStockID
, sooos.itemID
, i.itemNo
, i.itemName
, i.pack
, i.unitSize
, quantity
, wi.available
FROM SalesOrderOutOfStock sooos
JOIN Item AS i ON i.ItemID = sooos.ItemID
JOIN SalesOrder so ON so.SalesOrderID = sooos.SalesOrderID
JOIN WarehouseInventory wi ON wi.ItemID = sooos.ItemID
JOIN Store s ON s.StoreID = so.StoreID
JOIN InvoiceOrderRelationship ior ON ior.SalesOrderID = so.SalesOrderID
JOIN StockSale ss ON ss.WarehouseInvoiceNo = ior.WarehouseInvoiceNo
JOIN TransactionRegister tr ON tr.TransactionNo = ss.TransactionNo
JOIN Period p ON p.PeriodID = tr.PeriodID
JOIN Department d ON d.DepartmentID = i.DepartmentID
LEFT OUTER JOIN (SELECT TOP 1 itemID
, supplierID
FROM SupplierInvoiceDetail sid
JOIN SupplierInvoice si ON si.SupplierInvoiceID = sid.SupplierInvoiceID
--where (sid.ItemID = i.itemID)
order by InvoiceDate desc
--NEED AN ORDER BY HERE
) AS lastSupplier ON lastSupplier.ItemID = i.ItemID
JOIN supplier su ON su.SupplierID = Isnull(lastSupplier.supplierID, i.supplierID)
WHERE ss.WarehouseInvoiceNo = 10000000
- $ P {invoiceNo}
答案 0 :(得分:2)
您需要在此使用OUTER APPLY
而不是LEFT JOIN
:
OUTER APPLY (SELECT TOP 1 itemID
, supplierID
FROM SupplierInvoiceDetail sid
JOIN SupplierInvoice si ON si.SupplierInvoiceID = sid.SupplierInvoiceID
where (sid.ItemID = i.itemID) order by InvoiceDate desc
) AS lastSupplier
FROM
或JOIN
子句中引入的子查询不能引用同一FROM
子句中的其他表源(实际上,它们都应该可以同时评估) 。 APPLY
允许您在评估中引入特定的依赖关系。