3
I am servicing a bank and am finding it difficult to make a select.
Table structure descontos_taxas
:
id | value | client | data_created
My Scenario: This table holds both rates and discounts in the same table. Rates are positive values and discounts are negative values.
I need to take all the values of all customers, however, if a customer has received a fee and a discount on the same day I need to get only one result with the difference between the two.
So far I’ve done this:
SELECT
*
FROM
descontos_taxas as dt
WHERE
YEAR(dt.data_criado) = 2014 and MONTH(dt.data_criado) = 04 and dt.valor < 0
GROUP BY
dt.data_criado, dt.cliente
ORDER BY
data_criado asc;
How to return only negative amounts of the result of the sum of fees and discounts applied to the same customer? (Customers who do not have fees applied on the same day of the discount the amount would be added to 0).
I have this result in select:
valor | cliente | data_criado
-19,90 | Erlon Charles | 2014-04-01
9,90 | Erlon Charles | 2014-04-01
-19,90 | Erlon Charles | 2014-04-05
-19,90 | Erlon Charles | 2014-04-19
I need this result to match this:
valor | cliente | data_criado
-10,00 | Erlon Charles | 2014-04-01 //aqui estão os dados das tuplas 1 e 2 somados
-19,90 | Erlon Charles | 2014-04-05
-19,90 | Erlon Charles | 2014-04-19
what happens if you use the function
SUM()
mysql?– Bruno Rozendo
I did not get the correct value, I checked in some customers and was returned only the discount value and not the difference value. Example: a rate of 19.90 and a discount of -19.90, the select returns -19.90 when was to return 0.00.
– Erlon Charles
Important, in the database the values are saved with a signal . Otherwise we will need to use a case, something like (case when type=’D' then value * -1 Else end value)
– Motta
Yes values are saved with signal. I updated the question by entering an example of what I have and what I need to return.
– Erlon Charles
It has already been done in my answer, what is your doubt another thing the id can’t even appear there !!!
– user6026
I will still play your answer @Fccdias, was answering the question of others before testing your answer, so I check I put my considerations and if it is correct I mark, fine?
– Erlon Charles
Sure @Erloncharles, but, my aim is not to score was to help and my concern is if you had tested ok!
– user6026
I know, but marking how correct will help direct anyone who opens this question in the future
– Erlon Charles
Now I don’t know to whom I mark as correct, I took the tests and I needed to use the
HAVING
suggested by @Acco and the sums suggested by @fccdias to solve my problem– Erlon Charles