简体   繁体   中英

MySQL - How to get the difference of all the rows in a column within a specific “id”?

For example, in this table:

n   id   num

1   10   100
2   11    60
3   10    20
4   10    20
5   11    10

How do I subtract all the values of num (from top to bottom) with id = 10?

The first value of num in id=10 is subtracted to the 2nd value of num in id = 10 and the answer is subtracted to the third value of num in id = 10 (an so on and so forth if there are n numbers of num with the id =10)

It should display this:

difference of id = 10

50

Here is the working code you need:

SELECT AA.ID, (num_duo-total_sum) as num_diff FROM 

(SELECT id, 2*num as num_duo, MIN(n) FROM t1 GROUP BY id ) AA LEFT JOIN 


(SELECT id, SUM(num) as total_sum FROM t1 GROUP BY id) BB ON BB.id = AA.id 

SQL FIDDLE

If I understand correctly, you want to take the first value for the given id and then subtract subsequent values. "first" is defined by the first column, n .

If so, then this might help:

select sum(case when t.n = f.firstn then num else - num end)
from table t cross join
     (select min(n) as firstn
      from table t
      where id = 10
     ) f
where id = 10;

Here is a SQL Fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM