在sql中求和
Posted
技术标签:
【中文标题】在sql中求和【英文标题】:Sum a sum in sql 【发布时间】:2021-03-29 01:49:28 【问题描述】:早上好,我对 sql 很陌生,如果这是一个愚蠢的问题,我深表歉意
我试图通过出错来计算 totalcredit - totaldebit 的总和。如果我删除了总和(总和行我得到了 totaldebit 和 totalcredit 的计算结果),但我需要更进一步。
如果有人能告诉我哪里出错了,我将不胜感激
Sum(CASE WHEN dbt_crt = 'D' THEN sec_amount ELSE 0 END) as TotalDebit,
Sum(CASE WHEN dbt_crt = 'C' THEN sec_amount ELSE 0 END) as TotalCredit,
sum(sum(TotalDebit) - sum(TotalCredit)))
FROM test_securities_trans
group by client_acc, sec_isin
Started executing query at Line 207
Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ')'.
Total execution time: 00:00:00.011 ```
【问题讨论】:
【参考方案1】:您的问题是您两次使用聚合函数 sum(sum.....sum..)
和来自同一选择的别名(不允许在同一 select
中使用别名)。
只需使用:
Sum(CASE WHEN dbt_crt = 'D' THEN sec_amount ELSE 0 END) -
Sum(CASE WHEN dbt_crt = 'C' THEN sec_amount ELSE 0 END)
或者其他答案中描述的更简单的方法:
Sum(CASE WHEN dbt_crt = 'D' THEN sec_amount ELSE -1*sec_amount END)
【讨论】:
【参考方案2】:你需要重复表达式:
Sum(CASE WHEN dbt_crt = 'D' THEN sec_amount ELSE 0 END) as TotalDebit,
Sum(CASE WHEN dbt_crt = 'C' THEN sec_amount ELSE 0 END) as TotalCredit,
Sum(CASE WHEN dbt_crt = 'D' THEN sec_amount
WHEN dbt_crt = 'C' THEN - sec_amount
ELSE 0
END) as NetAMount,
您不能在 SELECT
中重复使用列别名。另外,SQL 不支持嵌套SUM()
s。
【讨论】:
【参考方案3】:您想计算同一行的差异,因此不需要嵌套聚合函数。您可以简单地添加另一个条件总和,如下所示:
sum(case when dbt_crt = 'c' then sec_amount else -sec_amount end) as totaldiff
这假定'C'
和'D'
是唯一可能的值(否则您将需要另一个WHEN
分支而不是ELSE
)。您可以使用WHERE
子句更明确地说明这一点:
select client_acc, sec_isin,
sum(case when dbt_crt = 'D' then sec_amount else 0 end) as totaldebit,
sum(case when dbt_crt = 'C' then sec_amount else 0 end) as totalcredit,
sum(case when dbt_crt = 'C' then sec_amount else -sec_amount end) as totaldiff
from test_securities_trans
where dbt_crt in ('C', 'D')
group by client_acc, sec_isin
【讨论】:
以上是关于在sql中求和的主要内容,如果未能解决你的问题,请参考以下文章