S
S
Sergey Volkov2018-07-17 14:53:21
MySQL
Sergey Volkov, 2018-07-17 14:53:21

How to calculate columns?

There is such a table. It is
lkXt0KLqcIw.jpg
necessary to write a query to get such a table:
mAPaCu4b2NA.jpg
I.e. in fact, there is a table of income / expenditure by the user of certain units, and you need to make a report where the rows will be, the user spent so much, received so much that, he has so much in total.
With my current understanding of SQL, queries are obtained for the same table and JOINs, and generally some kind of hell. I feel in my gut - all this is done in one request, but so far there are not enough brains. Tell me please.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Volkov, 2018-07-17
@srvr4vr

I found the answer myself:

SELECT user_id, SUM(CASE WHEN value<0 THEN value ELSE 0 END) as spent, 
SUM(CASE WHEN value>0 THEN value ELSE 0 END) as received, SUM(value) as total
FROM table
GROUP BY user_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question