[英]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? 如何减去id = 10的所有num值(从上到下)?
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) id = 10中num的第一个值减去id = 10中num的第二个值,答案减去id = 10时num第三个值(以此类推,如果有n个num,则以此类推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
If I understand correctly, you want to take the first value for the given id and then subtract subsequent values. 如果我理解正确,那么您想要获取给定id的第一个值,然后减去后续值。 "first" is defined by the first column,
n
. “第一”由第一列
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.