我有这个架构。我只对ItemNumber和ExternalInvoiceNUmber感兴趣。使用下面的代码
Select
StockItem.ItemNumber,
PurchaseItem.Quantity,
Purchase.ExternalInvoiceNumber,
PurchaseItem.Delivered
From
StockItem Left Join
PurchaseItem On PurchaseItem.fkStockItemId = StockItem.pkStockItemID Left Join
Purchase On Purchase.pkPurchaseID = PurchaseItem.fkPurchasId
结果并不完全是我想要的
ItemNumber Quantity ExternalInvoiceNumber Delivered
item1 10 PO9993 10
item1 10 PO9994 0
item1 10 PO9995 0
问题是我不希望任何包含项目记录的结果已经传递。我试着使用代码
where PurchaseItem.Delivered <> '0'
但是它不会显示任何只有1个externaminvoicenumber且已经交付的物品。基本上,我想要的是mssql不显示任何已传递的记录。但是,如果已交付采购订单,那么它应显示具有空白数量的项目和空白的外部资产。一个星期以来,我一直在讨论这个问题。你能帮我吗?
答案 0 :(得分:1)
您需要在JOIN条件下进行过滤。
在WHERE中,它变为INNER JOIN
...
Left Join
PurchaseItem On
PurchaseItem.fkStockItemId = StockItem.pkStockItemID
AND PurchaseItem.Delivered <> '0'
Left Join
...
或者,我喜欢分开JOIN和过滤器
的样式...
Left Join
(SELECT * FROM PurchaseItem WHERE Delivered <> '0') PurchaseItem
On PurchaseItem.fkStockItemId = StockItem.pkStockItemID
Left Join
...
答案 1 :(得分:0)
WITH DeliveredInvoice AS
(SELECT StockItem.ItemNumber as item, 0 as quant,
0 as ein, 0 as del
FROM StockItem
JOIN PurchaseItem ON PurchaseItem.fkStockItemId = StockItem.pkStockItemId
JOIN Purchase ON Purchase.pkPurchaseId = PurchaseItem.fkPurchaseId
WHERE PurchaseItem.Quantity > 0
AND PurchaseItem.Quantity = PurchaseItem.Delivered),
UndeliveredInvoice AS
(SELECT StockItem.ItemNumber as item, PurchasedItem.Quantity as quant, Purchase.ExternalInvoiceNumber as ein,
PurchaseItem.Delivered as del
FROM StockItem
JOIN PurchaseItem ON PurchaseItem.fkStockItemId = StockItem.pkStockItemId
JOIN Purchase ON Purchase.pkPurchaseId = PurchaseItem.fkPurchaseId
WHERE PurchaseItem.Delivered = 0)
SELECT item, quant, ein, del
FROM UndeliveredInvoice
UNION
SELECT item, quant, ein, del
FROM UndeliveredInvoice
WHERE item NOT IN (select distinct item from UndeliveredInvoice)