How can I use sum with a subquery inside?
The documentation for the function Sum () states that the parameter must be an expression. And, elsewhere, it cites that " (...) Aggregate functions and subqueries are not allowed ". That is, your code should be rewritten.
Sum () is one of several aggregation functions available in T-SQL. Generally, aggregation functions are used in conjunction with the GROUP BY clause, but can be used from isolated in some specific cases.
For example, to add the salaries paid in 2016 to each employee of the company, one 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 GROUP BY clause expressions and aggregate functions in addition to constants.
But if it is to 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, since all rows have been considered as a single group.
That said, you should consider each subquery as an individual query to apply the aggregate function usage rules.
Just as an example, to calculate the total salaries 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 queries, both internal and external, use the Sum () function, but in the case of the subquery there is the GROUP BY clause, since the sum is performed for each grouping.
Complementing, for good code readability as well as ease of maintenance, I suggest breaking the code into 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;