获取每个purchaseorderdetail id Adventureworks的供应商id

我想为 vendorID 中的每一行获取相应的 Purchasing.PurchaseOrderDetail。我正在使用 AdventureWorks2019。

PurchaseOrderDetail 中的行数:8,845。

加入供应商和产品供应商表时的行数:17,790

初始查询:

SELECT pod.*,VenDetails.[Name] AS VendorName
FROM Purchasing.PurchaseOrderDetail pod
LEFT JOIN Purchasing.ProductVendor PV ON pod.ProductID = PV.ProductID
LEFT JOIN Purchasing.Vendor VenDetails ON PV.BusinessEntityID = VenDetails.BusinessEntityID;

这会返回某些行的重复项,例如 WHERE PurchaseOrderDetailID = '8'

下一步,尝试使用PreferredVendorStatus

SELECT pod.*,VenDetails.[Name] AS VendorName,VenDetails.PreferredVendorStatus
FROM Purchasing.PurchaseOrderDetail pod
LEFT JOIN Purchasing.ProductVendor PV ON pod.ProductID = PV.ProductID
LEFT JOIN Purchasing.Vendor VenDetails ON PV.BusinessEntityID = VenDetails.BusinessEntityID;
WHERE VenDetails.PreferredVendorStatus = '1';

这将返回 13,344 行,但完全遗漏了一些行,例如 PurchaseOrderDetailID = '8' 并且仍然返回其他行的重复项,例如 PurchaseOrderDetailID = '11'

认为问题在于,有些供应商提供相同的产品并且具有相同的首选状态。

我也试过用

过滤连接
WHERE PV.OnOrderQty IS NOT NULL

并加入 TransactionHistory 上的 actualCost 表(这可能是业务的混合领域,不确定)。但是要么我在某些行上得到 NULL,要么重复。有人可以帮助我吗,我是否遗漏了一些明显的东西?

haifeng897 回答:获取每个purchaseorderdetail id Adventureworks的供应商id

结果我遗漏了明显的 - Purchasing.PurchaseOrderHeader 包含每个订单的 VendorID - 在详细信息表的联接中使用汇总表对我来说只是违反直觉。>

SELECT POD.*,PV.AverageLeadTime,PV.StandardPrice,Ven.[Name] AS VendorName,Ven.PreferredVendorStatus,PV.LastReceiptCost AS LastSellingPrice,PV.OnOrderQty AS CurrentlyOnOrder
FROM Purchasing.PurchaseOrderDetail POD
LEFT JOIN Purchasing.PurchaseOrderHeader POH ON POD.PurchaseOrderID = POH.PurchaseOrderID
LEFT JOIN Purchasing.ProductVendor PV ON POD.ProductID = PV.ProductID AND POH.VendorID = PV.BusinessEntityID
LEFT JOIN Purchasing.Vendor Ven ON Ven.BusinessEntityID = PV.BusinessEntityID
本文链接:https://www.f2er.com/2480.html

大家都在问