用零替换负值的问题

时间:2018-06-20 11:37:40

标签: sql case

检查了类似的线程,但其他用户未遇到类似的问题。

该代码似乎无法正常工作,并且错误消息显示“第11行出现意外的令牌'Then'”。

第6行到第8行获得确定节省量的计算列,但如果是损失,则变为负数。我想使用Case用0替换所有负值,但由于某种原因'then'被视为错误。

Select Distinct Reports.rptviewGovtTransparencyCode.project_title As Title,
  Reports.rptviewContract.AwardedDateTime As Awarded,
  Reports.rptviewContract.estimated_value As Budget,
  Convert(decimal,Replace(Reports.rptviewCustomFieldAnswer.Answer, ',',
  '')) As Value,
  Reports.rptviewContract.estimated_value -
  Convert(decimal,Replace(Reports.rptviewCustomFieldAnswer.Answer, ',',
  '')) As Saving,
  case when (Reports.rptviewContract.estimated_value -
  Convert(decimal,Replace(Reports.rptviewCustomFieldAnswer.Answer, ',', ''))
  <= 0 then 0) As Saving2
From Reports.rptviewGovtTransparencyCode
  Inner Join Reports.rptviewContract On Reports.rptviewContract.contract_id =
    Reports.rptviewGovtTransparencyCode.contract_id
  Inner Join Reports.rptviewCustomField On Reports.rptviewCustomField.OrgId =
    Reports.rptviewContract.OrgId
  Inner Join Reports.rptviewCustomFieldAnswer
    On Reports.rptviewCustomFieldAnswer.TargetAreaId =
    Reports.rptviewContract.project_id And Reports.rptviewCustomField.Id =
    Reports.rptviewCustomFieldAnswer.CustomFieldId
  Inner Join Reports.rptviewContractPrimaryContact
    On Reports.rptviewContract.contract_id =
    Reports.rptviewContractPrimaryContact.ContractId
Where Reports.rptviewGovtTransparencyCode.department = '1capital' And
  Reports.rptviewCustomField.Title = 'awarded value'

1 个答案:

答案 0 :(得分:0)

此:

case when (Reports.rptviewContract.estimated_value -
  Convert(decimal,Replace(Reports.rptviewCustomFieldAnswer.Answer, ',', ''))
  <= 0 then 0)

遗漏了案件的结尾,并且在when子句之后也有一个错误的括号对,将对号和“ then”括起来。将其替换为以下内容:

case when Reports.rptviewContract.estimated_value -
  Convert(decimal,Replace(Reports.rptviewCustomFieldAnswer.Answer, ',', ''))
  <= 0 then 0 end

为了更好地演示,您之前曾拥有过:

case when (condition then result)

正确的是

case when condition then result end

您不应在括号内隐藏“ then”:“何时”看不到。