我正在尝试运行此总和查询以生成两列“营业额”,一列用于TY,另一列用于LY。但是,我希望任何标记为“已取消”的交易都显示为负数:
select [Location],BR.BranchName,
sum(case when (FX.TransactionDateKey between '20171101' and '20181031')
and ([Action] = 'Cancelled')
then FX.CustomerValue*-1 else [CustomerValue] end) as [CustmVal TY],
sum(case when (FX.TransactionDateKey between '20161101' and '20171031')
and ([Action] = 'Cancelled')
then FX.CustomerValue*-1 else FX.CustomerValue*1 end) AS [CustmVal LY]
from [dbo].[FRX_Transactions] FX
inner join DWX_Branch BR on BR.BranchID=FX.[Location]
where FX.TransactionDateKey between '20161101' and '20181031' and BR.BusinessDivision = 'Retail'
and FX.[Action] in ('Trade','cancelled') and FX.Reason in ('Public','BBG','Overridesupplyrate') and FX.Operation in ('Add','Del')
group by FX.[Location],BR.BranchName, BR.BranchOpenDate,BR.BranchCloseDate,BR.ActiveStatus
order by BR.BranchName
但是,当我运行它时,我在两列中都得到了类似的数据-似乎忽略了日期条件。 拜托,我在做什么错?带有两个条件的案例陈述是否写错了?
任何帮助将不胜感激。非常感谢!
答案 0 :(得分:1)
我认为您实际上想要CASE
表达式是:
CASE WHEN FX.TransactionDateKey BETWEEN '20171101' AND '20181031' THEN [CustomerValue] *
CASE WHEN [Action] = 'Cancelled' THEN -1 ELSE 1 END
END