1
I have a query where I have 3 columns grouped and last totaling 3, the problem is for Edson the query is not TOTALING.
TOTAL = CREDIT - (DISCOUNT + REBATES)
The total Edson has to give 266,49 but my code does not calculate, due to the "discount" still be NULL.
SELECT
U.NOME,
CAST(SUM(R.CAMPOCALC1) as NUMERIC (15,2)) AS CREDITO_FLEX,
CAST(SUM(R.CAMPOCALC2) AS NUMERIC(15,2)) AS DESCONTO_PRODUTOS_FLEX,
CAST(SUM(R.CAMPOCALC3) AS NUMERIC(15,2)) AS BONIFICACOES,
CAST(SUM(R.CAMPOCALC1) as NUMERIC (15,2)) - CAST(SUM(R.CAMPOCALC3) AS NUMERIC(15,2)) - CAST(SUM(R.CAMPOCALC2) AS NUMERIC(15,2)) AS TOTAL_FLEX_VENDEDOR
FROM
COTACAOI R
LEFT JOIN COTACAO C ON R.ID_COTACAO = C.ID
LEFT JOIN CADUSUARIO U ON C.ID_VENDEDOR = U.ID
WHERE
R.ID_PEDIDO IS NOT NULL AND
R.CAMPOADICIONAL1 = 'SIM'
GROUP BY
U.NOME
"Edson’s total has to be 266.49 but my code doesn’t calculate" can you put an example with the table data that has to give this result? Pq cast, what is the data type of CAMPOCALC1, CAMPOCALC2 and CAMPOCALC3 columns?
– Ricardo Pontual
You have to understand the meaning of
NULL
. NULL means that the value of that attribute is unknown, is an absence of value, so any operation involving NULL will result in NULL. Up to a comparison, using one of the comparison operators (>
,<
.=
,!=
,>=
or<=
) involving a NULL will result in NULL. SQL provides a special operator for you to verify whether or not a field is NULL, theIS NULL
andIS NOT NULL
.– anonimo
If, for special reasons of your application, you want to consider as zero a field that contains NULL use the COALESCE function:
COALESCE(campo, 0)
. This function can have a list of fields as parameters and will return the first field not NULL. For your caseSUM(COALESCE(R.CAMPOCALC1,0))
and the same thing in other accumulations.– anonimo
@Ricardopunctual the example was above, total = credit - (discount + bonuses) on the cast is changing the number of digits after the comma... all data are numerical.
– Vinicius Ferreira
This is why it is important to set a default value for columns that store values with 0. Always. And restrict the ability to save null. NOT NULL
– Mateus