简体   繁体   English

MySQL-如何获取特定“ id”内一列中所有行的差值?

[英]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 

SQL FIDDLE SQL字段

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;

Here is a SQL Fiddle. 是一个SQL Fiddle。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在MySQL的分页查询中获取5行内的特定ID - how to get a specific id within 5 rows in a paging query in Mysql 我如何使用MySQL在Laravel中的大型数据库中快速搜索特定ID并获取该ID的所有行? - How can i quickly search a specific id and get all rows of that id in a large database in Laravel with mysql? MySQL根据特定的列值获取所有行(按列过滤) - MySQL get all rows based on a specific column value (filter by column) MySQL-在另一列上获取具有相同ID但特定值不同的行 - MySQL - get rows with same ID but different specific values on another column 如何获取所有行,其中特定列=不同表中另一行的ID - how to get all rows where specific column = id of other row in different table 如何减少MySQL表中所有行的id列? - How can I decrease an `id` column on all rows in a MySQL table? 如何使用MySQL将ID的所有列值回显到行中 - How to echo all column values of an id into rows using mysql 获取具有特定时差的所有行 - Get all rows with specific time difference 如何使用mysql获取所有行的一列中的时间总和 - How to get the sum of time in a column of all rows using mysql 对于特定的user_id,在MySQL中获取该用户与所有其他用户一起的最新行(按时间) - For a specific user_id get the latest rows (time-wise) that this user is in with all other users, in MySQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM