Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I subtract two row's values within same column using sql query?

Tags:

sql

I want to display the subtraction of two values from two different rows using a SQL query.

This is the table structure:

------------------------------------
id | name | sub1 | sub2 | date
------------------------------------
1  | ABC  | 50   | 75   | 2014-11-07
2  | PQR  | 60   | 80   | 2014-11-08  

I want to subtract date 2014-11-08 subject marks from date 2014-11-07.

Output should be like as

| sub1  | sub2 |
 ---------------
|   10  |   5  |
like image 590
Talk2Nit Avatar asked Nov 08 '14 12:11

Talk2Nit


1 Answers

You can use a join to get the rows and then subtract the values:

SELECT(t2.sub1 - t1.sub1) AS sub1, (t2.sub2 - t1.sub2) AS sub2
FROM table t1 CROSS JOIN
     table t2
WHERE t1.date = '2014-11-08' AND t2.id = '2014-11-07';
like image 191
Gordon Linoff Avatar answered Sep 21 '22 19:09

Gordon Linoff