我需要得到每一行的总数,但我不能为行提取别名,因为它会给出错误。如何在下面的语句中获取行的sum()。
select sum(Amount) as [Amount total],
sum(balance) as [Balance Total],
sum(Remaining) as [Remaining Total]
from MyTable
我想做点什么
select sum(Amount) as [Amount total],
sum(balance) as [Balance Total],
sum(Remaining) as [Remaining Total],
[Amount total]+[Balance Total]+[Remaining Total] as Total
from MyTable
答案 0 :(得分:2)
重复表达式,使用子查询或使用CTE。这是第一选择:
select sum(Amount) as [Amount total],
sum(balance) as [Balance Total],
sum(Remaining) as [Remaining Total],
(sum(Amount) + sum(balance) + sum(Remaining)) as Total
from MyTable;
列别名在定义它们的同一级别无法识别。
答案 1 :(得分:1)
试试这个:
SELECT SUM(Amount) AS [Amount total],
SUM(balance) AS [Balance Total],
SUM(Remaining) AS [Remaining Total],
SUM(Amount + balance + Remaining) AS Total
FROM MyTable
答案 2 :(得分:0)
您不必对SUMS进行求和,只需对它们正在求和的列进行求和,您将获得总和:
select sum(Amount) as [Amount total],sum(balance)[Balance Total]
,sum(Remaining)[Remaining Total],SUM(Amount+Balance+Remaining) as Total
from MyTable