为什么不匹配?

时间:2018-12-04 20:41:45

标签: sql sql-server

代码:

(SELECT 
[QBDATABASE].[dbo].[itemnoninventory].[FullName],
[LotTracker].[dbo].[tblParts].[PartNo],
[QBDATABASE].[dbo].[itemnoninventory].[CustomField2] AS StdCost,
[QBDATABASE].[dbo].[salesorpurchasedetail].[Price],
[QBDATABASE].[dbo].[itemnoninventory].[ListID],
[QBDATABASE].[dbo].[salesorpurchasedetail].[IDKEY]
FROM 
[QBDATABASE].[dbo].[itemnoninventory]
Inner JOIN
[QBDATABASE].[dbo].[salesorpurchasedetail] ON [QBDATABASE].[dbo].[itemnoninventory].[ListID] = [QBDATABASE].[dbo].[salesorpurchasedetail].[IDKEY]
INNER JOIN 
[LotTracker].[dbo].[tblParts] ON [QBDATABASE].[dbo].[itemnoninventory].[FullName] like [LotTracker].[dbo].[tblParts].[PartNo]
WHERE ([QBDATABASE].[dbo].[salesorpurchasedetail].[AccountRef_FullName] = 'Inventory, Raw Material')

我添加了不必要的选择,以创建示例结果下方的屏幕截图。

enter image description here

ListID is varchar(255), null)
IDKEY is varchar(255), null)

问题:

是什么会导致查询无法看到ListID = IDKEY结果的NULL

修改目标:

如果StdcostPrice

ListID=IDKEY应该与FullName=PartNo金额匹配

3 个答案:

答案 0 :(得分:1)

这不是答案,但评论太久。在这里您完全相同的查询。我所做的唯一更改是格式化了一点,并删除了所有那些长得令人讨厌的对象名称,并改用了别名。

SELECT 
    ini.FullName,
    p.PartNo,
    ini.CustomField2 AS StdCost,
    spd.Price,
    ini.ListID,
    spd.IDKEY
FROM QBDATABASE.dbo.itemnoninventory ini
Inner JOIN QBDATABASE.dbo.salesorpurchasedetail spd ON ini.ListID = spd.IDKEY
INNER JOIN  LotTracker.dbo.tblParts p ON ini.FullName like p.PartNo
WHERE spd.AccountRef_FullName = 'Inventory, Raw Material'

您的问题的答案是itemnoninventory中的行包含NULL,因此在查询中它当然将为NULL。

答案 1 :(得分:0)

编辑后,如果CustomField2为null,则需要返回价格。可以使用ISNULL或COALESCE来完成。如果第一个值为空,则ISNULL将返回第二个值。

(SELECT 
[QBDATABASE].[dbo].[itemnoninventory].[FullName],
[LotTracker].[dbo].[tblParts].[PartNo],
ISNULL([QBDATABASE].[dbo].[itemnoninventory].[CustomField2],[QBDATABASE].[dbo].[salesorpurchasedetail].[Price]) AS StdCost,
[QBDATABASE].[dbo].[salesorpurchasedetail].[Price],
[QBDATABASE].[dbo].[itemnoninventory].[ListID],
[QBDATABASE].[dbo].[salesorpurchasedetail].[IDKEY]
FROM 
[QBDATABASE].[dbo].[itemnoninventory]
Inner JOIN
[QBDATABASE].[dbo].[salesorpurchasedetail] ON [QBDATABASE].[dbo].[itemnoninventory].[ListID] = [QBDATABASE].[dbo].[salesorpurchasedetail].[IDKEY]
INNER JOIN 
[LotTracker].[dbo].[tblParts] ON [QBDATABASE].[dbo].[itemnoninventory].[FullName] like [LotTracker].[dbo].[tblParts].[PartNo]
WHERE ([QBDATABASE].[dbo].[salesorpurchasedetail].[AccountRef_FullName] = 'Inventory, Raw Material')

答案 2 :(得分:0)

我不能投票。我结合了两个肖恩的回答,并得到了我想要的。都是。

SELECT 
    ini.FullName,
    p.PartNo,
    ISNULL(ini.CustomField2,spd.Price) AS StdCost,
    spd.Price,
    ini.ListID,
    spd.IDKEY
FROM QBDATABASE.dbo.itemnoninventory ini
Inner JOIN QBDATABASE.dbo.salesorpurchasedetail spd ON ini.ListID = spd.IDKEY
INNER JOIN  LotTracker.dbo.tblParts p ON ini.FullName like p.PartNo
WHERE spd.AccountRef_FullName = 'Inventory, Raw Material'