Reputation: 540
I need to get total of each row, but i can't take the alias name for the row as it gives error. How to get sum() for the row in the below statement.
select sum(Amount) as [Amount total],
sum(balance) as [Balance Total],
sum(Remaining) as [Remaining Total]
from MyTable
I want to do something like
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
Upvotes: 0
Views: 772
Reputation: 31785
You don't have to SUM the SUMS, just SUM the columns that they are SUMming, and you will get the total sum:
select sum(Amount) as [Amount total],sum(balance)[Balance Total]
,sum(Remaining)[Remaining Total],SUM(Amount+Balance+Remaining) as Total
from MyTable
Upvotes: 0
Reputation: 29051
Try this:
SELECT SUM(Amount) AS [Amount total],
SUM(balance) AS [Balance Total],
SUM(Remaining) AS [Remaining Total],
SUM(Amount + balance + Remaining) AS Total
FROM MyTable
Upvotes: 1
Reputation: 1269773
Repeat the expression, use a subquery, or use a CTE. Here is the first choice:
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;
Column aliases are not recognized at the same level where they are defined.
Upvotes: 2