MS SQL!=和<>条款没有显示所有差异

时间:2017-01-20 09:00:32

标签: sql sql-server

我的sql查询有问题。它只显示100%的差异,
在第7行“OrSp_Amount!= OrSp_CompletedAmount”的WHERE子句中。

首先选择工作正常,但第二个选择没有显示出部分差异。 (20-5,40-3,例如只有45-0)

我尝试过使用'<>'它也没有改变。

任何想法:)?

WITH Orders_CTE
AS
(
    SELECT  [OrSp_ProductInWarehouseId], [OrSp_CompletedFromInvoice], [OrSp_Amount], [OrSp_TaxRate], [OrSp_CompletedAmount], OrSp_Price ,
     OrSp_OrderHeaderId , Orde_ClientId
    FROM  data.AllOrders 
    JOIN [data].[AllOrderPositions]WITH(INDEX([IX_OrSp_OrderHeaderId])) ON [Orde_Id] = [OrSp_OrderHeaderId]
    WHERE [Orde_ShipmentDate] BETWEEN '2016-06-01' AND '2017-01-01' AND [Orde_ClientId] = 17467  AND  OrSp_Amount != OrSp_CompletedAmount
)

    SELECT  OrSp_ProductInWarehouseId, 17467 as ClientID, 
    SUM(Orders_CTE.OrSp_Price) as Price,
    SUM(OrSp_Amount) as Amount, 
    SUM(OrSp_Price * OrSp_Amount) as TotalNetValue ,
    SUM(OrSp_CompletedFromInvoice) as CompletedFromInvoice,
    SUM(OrSp_CompletedAmount) as CompletedAmount,
    SUM(OrSp_Price * OrSp_CompletedFromInvoice) as CompletedValue,
    SUM(OrSp_CompletedFromInvoice) / nullif(SUM(OrSp_Amount),0) as AmountRealizationPlaceholder,
    SUM(OrSp_TaxRate*OrSp_Price + OrSp_Price) * SUM(OrSp_CompletedFromInvoice) / nullif(SUM((OrSp_TaxRate * OrSp_Price) + OrSp_Price),0) * SUM(OrSp_Amount) as ValueRealizationPlaceholder
    FROM Orders_CTE JOIN [data].[Products] as Products ON Orders_CTE.OrSp_ProductInWarehouseId = Prod_Id 
    GROUP BY OrSp_ProductInWarehouseId, OrSp_OrderHeaderId

2 个答案:

答案 0 :(得分:1)

由于无法使用比较运算符测试NULL值,因此如果字段OrSp_Amount或OrSp_CompletedAmount的值为NULL,则无法获得任何有意义的结果。

您可以尝试将WHERE子句更改为:

COALESCE(OrSp_Amount, 0) <> COALESCE(OrSp_CompletedAmount, 0)

答案 1 :(得分:0)

问题已解决。我忘了在第二个SELECT中加入“LEFT”,并且一些值大于0的记录被“丢失”。