Subtract a value from a sum (SUM) in SQL?

0

Good afternoon! I have a SQL query, which fetches and adds the amount of credits a given user has:

SELECT *, SUM(quantidade) as total_creditos FROM creditos INNER JOIN usuarios ON creditos.id_usuario = usuarios.id WHERE creditos.id_usuario = '$id_usuario''

In the credits table, I have the following structure:

A user can have multiple inserts in the table, with X credits.

The question is: how can I make a query and decrease (delete) a Y value of a user's total SOMA credits?

Thank you in advance!

    
asked by anonymous 30.05.2017 / 20:11

1 answer

1

Since you are dynamically doing a sum total of credit amounts, there is no way to permanently lower some of that amount directly. You will need to somehow enter this amount to be discounted.

I think of two different paths that can be followed:

  • Create a new table where the debits of users will be posted and in your query add this table and subtract these values from credits debits to know the balance of the user (s)

    li>
  • Use the same credit table, making postings with negative credit value for the user (s) in question. That way the changes would be minimized.

The first option seems to be more elegant and robust, the second more practical.

    
30.05.2017 / 20:58