[英]MySQL - How to get the difference of all the rows in a column within a specific “id”?
例如,在此表中:
n id num
1 10 100
2 11 60
3 10 20
4 10 20
5 11 10
如何减去id = 10的所有num值(从上到下)?
id = 10中num的第一个值减去id = 10中num的第二个值,答案减去id = 10时num第三个值(以此类推,如果有n个num,则以此类推id = 10)
它应该显示以下内容:
difference of id = 10
50
这是您需要的工作代码:
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
如果我理解正确,那么您想要获取给定id的第一个值,然后减去后续值。 “第一”由第一列n
定义。
如果是这样,那么这可能会有所帮助:
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;
这是一个SQL Fiddle。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.