SQL-SUM TotalValue使用LEFT JOIN子句返回null

时间:2019-01-31 08:43:49

标签: sql sql-server

我想对SUM基于供应商和已登录用户的TotalValue列进行求和。我在登录的用户和连接的供应商中完全返回了其他信息的正确值,问题是TotalValue列的SUM返回空值。我错过了什么吗?

这是我已经尝试过的:

SELECT ,v.VendorName ,
        u.Product ,
        v.[Description] ,
        v.Status ,
        SUM(cpm.TotalValue) AS TotalValue
FROM Vendor v
LEFT JOIN [ProductContract] c ON v.VendorId = c.VendorId
AND c.[Status] = 4
AND c.ProductContractId IN
  (SELECT con.ProductContractId
   FROM [ProductContract] con
   INNER JOIN [ProductContractPermission] cp ON cp.ProductContractId = con.ProductContractId
   WHERE cp.UserInfoId = @UserInfoId)
LEFT JOIN ProductContractPaymentMenu cpm ON c.ProductContractId = cpm.ProductContractId
AND c.[Status] = 4
AND c.VendorId = @VendorId
LEFT JOIN VendorContact vc ON v.VendorId = vc.VendorId
AND vc.[Type] = 1
LEFT JOIN UserInfo u ON vc.UserInfoId = u.UserInfoId
WHERE v.VendorId IN
    (SELECT VendorId
     FROM ClientVendor
     WHERE ClientId = @VendorId)
GROUP BY v.VendorName,
         u.Product,
         v.[Description],
         v.Status,
         cpm.TotalValue
ORDER BY v.[Status],
         v.CreatedOn

3 个答案:

答案 0 :(得分:1)

似乎您要应用聚合过滤器,这是著名的HAVING子句:

...
GROUP BY v.VendorName,
         u.Product,
         v.[Description],
         v.Status,
         cpm.TotalValue
HAVING
    SUM(cpm.TotalValue) > 0
ORDER BY v.[Status],
         v.CreatedOn

答案 1 :(得分:0)

嗨,我认为您必须添加ISNULL(value,defaultvalue),因为cpm表位于左联接上,并且可以为null。

SELECT v.VendorName ,
        u.Product ,
        v.[Description] ,
        v.Status ,
        SUM(ISNULL(cpm.TotalValue,0)) AS TotalValue
FROM Vendor v
LEFT JOIN [ProductContract] c ON v.VendorId = c.VendorId
AND c.[Status] = 4
AND c.ProductContractId IN
  (SELECT con.ProductContractId
   FROM [ProductContract] con
   INNER JOIN [ProductContractPermission] cp ON cp.ProductContractId = con.ProductContractId
   WHERE cp.UserInfoId = @UserInfoId)
LEFT JOIN ProductContractPaymentMenu cpm ON c.ProductContractId = cpm.ProductContractId
AND c.[Status] = 4
AND c.VendorId = @VendorId
LEFT JOIN VendorContact vc ON v.VendorId = vc.VendorId
AND vc.[Type] = 1
LEFT JOIN UserInfo u ON vc.UserInfoId = u.UserInfoId
WHERE v.VendorId IN
    (SELECT VendorId
     FROM ClientVendor
     WHERE ClientId = @VendorId)
GROUP BY v.VendorName,
         u.Product,
         v.[Description],
         v.Status,
         cpm.TotalValue
ORDER BY v.[Status],
         v.CreatedOn

https://docs.microsoft.com/en-us/sql/t-sql/functions/isnull-transact-sql?view=sql-server-2017

编辑:SELECT之后在查询中其他地方缺少'。'。

答案 2 :(得分:0)

您在ads:adSize="FULL_WIDTHx50"上的左联接可能并不总是得到项,因此ProductContractPaymentMenu有时可以是cpm.TotalValue。当您使用NULL且一个值为SUM时,结果将为NULL。您可以将该部分重写为:

NULL

在这种情况下,它将不存在的记录视为值0。