How can I use sum with a subquery inside?
Documentation of the function Sum() indicates that the parameter must be an expression. And, in another part, it states that "(...) Aggregation functions and sub-discharge is not permitted". That is, your code must be rewritten.
Sum() is one of several aggregation functions available in T-SQL. Generally the aggregation functions are used in conjunction with the clause GROUP BY, but may be used in isolation in some specific cases.
For example, to add up the salaries paid in 2016 to each employee of the company, a way would be:
-- código #1
SELECT P.idFunc, Sum(P.Salário_Mensal) as Salário_Anual
from Pagamento as P
where P.AnoPagamento = 2016
group by P.idFunc;
Note that the column list can only contain expressions of the GROUP BY clause and aggregation functions, as well as constants.
But if we add up all the salaries paid in 2016, we can have:
-- código #2
SELECT Sum(P.Salário_Mensal) as Total_salários
from Pagamento as P
where P.AnoPagamento = 2016;
In this case there is no GROUP BY clause as all lines were considered as a single group.
That being said, you should consider each sub-allowance as an individual query to apply the rules of use of the aggregation function.
Just as an example, to calculate the total wages paid in 2016 we can have
-- código #3
SELECT Sum(Salário_Anual) as Total_salários
from (SELECT P.idFunc, Sum(P.Salário_Mensal) as Salário_Anual
from Pagamento as P
where P.AnoPagamento = 2016
group by P.idFunc
) as T;
Note that both internal and external queries use the Sum() function, but in the case of the sub-consultation there is the GROUP BY clause, because the sum is performed for each grouping.
Complementing, for good readability of the code, as well as facilitating maintenance, I suggest you break the code in parts, using CTE. This is possible when there is no correlation between queries. For example:
-- código #4
with Salários_Func as (
SELECT P.idFunc, Sum(P.Salário_Mensal) as Salário_Anual
from Pagamento as P
where P.AnoPagamento = 2016
group by P.idFunc
)
SELECT Sum(Salário_Anual) as Total_salários
from Salários_Func;
What returns when you do only subselect?
– Reginaldo Rigo
Has any response helped solve the problem and can address similar questions from other users? If so, make sure to mark the answer as accepted. To do this just click on the left side of it (below the indicator of up and down votes).
– Sorack