G
G
gibigate2016-02-17 15:55:18
MySQL
gibigate, 2016-02-17 15:55:18

Subtraction and addition in mysql query?

There is a table:
id | date | number1 | number2
3 | 2016-02-17 | 200 | 100
.....
2 | 2016-02-15 | 300 | 100
......
1 | 2016-02-13 | 100 | 50
Help me make a query:
You need to take the number1 and number2 values ​​from the id2 cell and subtract the values ​​from id 1
from them, then add number1 and number2 to the id3
values, that is, $result = id3 + (id2 - id1)
You can only cling to the date

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
Walt Disney, 2016-02-18
@gibigate

Although I don’t really know why the line / record is called a cell, why the brackets before the plus and what it is to cling to.
But the query below will do what you want.

SELECT 
SUM(IF(date = '2016-02-13',0-number1,number1)) as number1,
SUM(IF(date = '2016-02-13',0-number2,number2)) as number2
 FROM table 
 WHERE `date` IN('2016-02-17','2016-02-15','2016-02-13')

I
Igor, 2016-02-17
@unitby

I don’t know how to do it right, but you can get the desired result with something like this query
select ( (select sum(number1) from table where date in ('2016-02-15', '2016-02-17' )) - (select sum( number1) from table where date in ('2016-02-13')) ), ( (select sum(number2) from table where date in ('2016-02-15', '2016-02-17' )) - (select sum(number2) from table where date in ('2016-02-13')) )

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question