如何选择和求和mysql中特定行的值

时间:2016-01-16 10:29:04

标签: mysql

我想从MySQL中总结特定行的值,就好像我的表包含2列id和名称具有值

|id |name   |
|1  |yatin  |
|2  |max    |
|3  |josh   |
|4  |bob    |
|5  |mary   |
|6  |jane   |

我想从名称max到mary中选择行,并将它们的id相加,这样我就可以了 |值| | 14 |

2 个答案:

答案 0 :(得分:1)

E.g:

SELECT SUM(a.id) total 
  FROM my_table a 
  JOIN my_table x 
    ON x.id <= a.id 
  JOIN my_table y 
    ON y.id >= a.id 
 WHERE x.name = 'max' 
   AND y.name = 'mary';

答案 1 :(得分:0)

SELECT SUM(id) FROM yourtable WHERE id BETWEEN 4 AND 8;

SELECT SUM(id) FROM yourtable WHERE id > 3 AND id < 9;

等...