[英]SQL query: NULL values that should not be NULL when using aggregate function with left join
i dont have much expiriance with SQL and i am trying to crack my head on this query. 我对SQL的了解不多,我正试图在此查询上打起精神。 i have 3 tables: Projects, Calculator and partialBilling (note: the 'calculator' columns you see at the code ive added 'k','l','m' etc are real...i didnt gave them those names...). 我有3个表:Projects,Calculator和partialBilling(注意:您在代码ive上看到的'calculator'列添加了'k','l','m'等,是真实的...我没有给他们提供这些名称。 )。
the query is working fine but part of the values that i am expecting from the aggregate function ('sumofTotal' column) are returning as null values and and they should not be null. 查询工作正常,但我从聚合函数(“sumofTotal”列)期待值的一部分返回为空值,而且,他们不能为空。 I would be grateful if someone point out the mistake in the query. 如果有人指出查询中的错误,我将不胜感激。
SELECT Projects.SpCall,Projects.CustName,Projects.CustNumber
,Projects.ReceiveDate,Projects.StartDate,Projects.ProjectType
,Calculator.AN,Projects.Professional,Projects.PmUserName
,Projects.AcountManager,Projects.CrmCallNum,Projects.ProjectCategory
,Projects.CallNum,Projects.ContactName,Projects.ContactPhone
,Projects.ContactEmail,Projects.HiddenNote,Projects.RowColor
, Projects.HeaderCellText,
SUM(Calculator.K + Calculator.L + Calculator.M + Calculator.N + Calculator.AD + Calculator.AR) AS sumofTotal
,partialBilling.Ammount FROM Projects LEFT JOIN Calculator ON Projects.SpCall=Calculator.AQ
LEFT JOIN partialBilling ON Projects.SpCall = partialBilling.spCall
WHERE PmUserName= 'JOHN DOE'AND OpertionalStatus
<> 'Billed' AND OpertionalStatus<> 'Finished' AND
OpertionalStatus<> 'Passed To Billing' AND OpertionalStatus<> 'Scanning'
AND OpertionalStatus<> 'Ended'
AND OpertionalStatus<> 'Green Billing'
AND (GeneralStatus= 'Passed To Project Manager'
OR GeneralStatus= 'Astrategic Project')
GROUP BY Projects.SpCall,Projects.CustName,Projects.CustNumber
,Projects.ReceiveDate,Projects.StartDate,Projects.ProjectType
,Calculator.AN,Projects.Professional,Projects.PmUserName
,Projects.AcountManager,Projects.CrmCallNum,Projects.ProjectCategory
,Projects.CallNum,Projects.ContactName,Projects.ContactPhone
,Projects.ContactEmail,Projects.HiddenNote,Projects.RowColor
, Projects.HeaderCellText,partialBilling.Ammount;
尝试使用IFNULL()
SUM(IFNULL(Calculator.K,0) + ... + IFNULL(Calculator.AR,0)) AS sumofTotal
Instead of proprietary IFNULL
better use Standard SQL COALESCE
: 最好使用Standard SQL COALESCE
而不是专有的IFNULL
:
SUM(COALESCE(Calculator.K,0) + COALESCE(Calculator.L,0), ...`
Or maybe a bit more efficient: 也许更有效率:
SUM(COALESCE(Calculator.K,0)) + SUM(COALESCE(Calculator.L,0)), ...`
您可以使用ifnull('column_name' , '')
类的表达式代替column_name
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.