如何解决带乘法变量的表达式
我正在制作一份基于借方和贷方报告的财务报告。如果满足某些条件,我想编写一个表达式,该表达式将取数量并将其乘以 -1。应该是这样的:
IF AccountClass = Revenue,Sum Amount *-1,IF AccountClass = Expenditure,Sum Amount *1
我使用的是 sql Server 2012 和 Microsoft sql Server 报表生成器。报告结果如下所示:
账户类 | 数量 |
---|---|
收入 | 2,498.04 |
收入 | -10,500.03 |
支出 | 500.00 |
支出 | 700.00 |
我希望它显示如下:
账户类 | 数量 |
---|---|
收入 | -2,498.04 |
收入 | 10,500.03 |
支出 | 500.00 |
支出 | 700.00 |
想法?
在数据集查询中,我添加了一个 CASE THEN WHEN 表达式,将 AccountClass Revenue 设置为 Category 1,AccountClass Expenditure 设置为 Category 2。然后我创建了这个表达式来计算总和本身:
=Sum(VAL(IIF(Fields!Category.Value = "Category 1",Fields!Amount.Value,0)*-1))
但我只能让它适用于第 1 类或第 2 类,我不知道如何让它同时适用于两者。类别 2 将类似,但 *1。
这是完整的查询:
SELECT
Custom1.Account,Custom1.AccountClass,Custom1.Description,Custom1.[Year],@Quarter as [Quarter],Custom1.Budget,CASE WHEN Custom1.AccountClass = 'Revenue' THEN 'Category 1'
WHEN Custom1.AccountClass = 'Expenditure' THEN 'Category 2'
ELSE 'Category 3'
END AS 'Category',SUM(Custom1.Amount) as Amount,(SELECT ISNULL(SUM(t.[Amount for Balance]),0) FROM [Transactions] t WHERE t.[Account Number] = Custom1.Account AND t.[Fiscal Year] = @Year and t.[Period Number] <= @QuarterEnd) as YearToDate,SUM(Custom2.Amount) as AmountLastYear,0) FROM [Transactions] t WHERE t.[Account Number] = Custom1.Account AND t.[Fiscal Year] = CONVERT(INTEGER,DATEPART(year,@Year)) - 1 and t.[Period Number] <= @QuarterEnd) as YearToDateLastYear
FROM [Account Details by Period] AS Custom1
LEFT JOIN [Account Details by Period] AS Custom2 ON Custom1.AccountID = Custom2.AccountID AND DATEPART(year,Custom2.FiscalYearEnd) = CONVERT(INTEGER,Custom1.FiscalYearEnd)) - 1 AND Custom1.Period = Custom2.Period
WHERE DATEPART(year,Custom1.FiscalYearEnd) = @Year
AND Custom1.AccountClass IN (N'Revenue',N'Expenditure')
AND @Quarter = CASE WHEN Custom1.Period BETWEEN 1 AND 3 THEN 'Q1'
WHEN Custom1.Period BETWEEN 4 AND 6 THEN 'Q2'
WHEN Custom1.Period BETWEEN 7 AND 9 THEN 'Q3'
WHEN Custom1.Period BETWEEN 10 AND 12 THEN 'Q4'
END
AND @Quarter = CASE WHEN Custom2.Period BETWEEN 1 AND 3 THEN 'Q1'
WHEN Custom2.Period BETWEEN 4 AND 6 THEN 'Q2'
WHEN Custom2.Period BETWEEN 7 AND 9 THEN 'Q3'
WHEN Custom2.Period BETWEEN 10 AND 12 THEN 'Q4'
END
GROUP BY Custom1.Account,Custom1.Budget
ORDER BY Custom1.Account
解决方法
使用 case
,您需要提供示例数据但
如果 AccountClass 条件适用于每个金额:
select sum((case when AccountClass = 'Revenue' then -1 else 1 end) * amount)
from table
...
如果 AccountClass 条件适用于整个 sum() 值,则
select sum(amount) * (case when AccountClass = 'Revenue' then -1 else 1 end)
from table
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。