简体   繁体   English

mysql从同一列中的不同行中减去

[英]mysql subtraction from different rows in same column

I have a table for mileage records. 我有一张里程记录表。 Like this sample one. 像这个样本之一。 I need to calculate mileage usage for particular month. 我需要计算特定月份的里程使用情况。

Date            Meter
---------------------
2014-01-01      12500
2014-01-12      12650
2014-02-01      13000
2014-02-15      13350
2014-03-01      15000

I need an answer for example: for January the result is 500 (from the subtraction 13000-12500 ) or for February the reuslt is 2000 ( 15000-13000 ). 我需要一个答案,例如:一January的结果是500 (减去13000-12500 ), February的结果是200015000-13000 )。

I tried the following but I'm getting the wrong answer. 我尝试了以下操作,但得到的答案错误。 How do I get about this? 我该怎么办? Thank you. 谢谢。

select (select Meter from tbl where Date = '2014-12-01') - 
       (select Meter from tbl where Date = '2014-11-01');

Try this: 尝试这个:

SELECT EXTRACT(MONTH FROM t1.`Date`) AS month,
       t2.Meter - t1.Meter
FROM mytable AS t1
JOIN mytable AS t2 ON t2.`Date` =  DATE_ADD(t1.`Date`, INTERVAL 1 MONTH)
WHERE EXTRACT(DAY FROM t1.`Date`) = 1

This should work as long as you have one record for each 1st day of month date. 只要您在每月第1天的每一天都有一条记录,就可以使用此功能。

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

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