Énorme avis de non-responsabilité : Cela vient avec non garantie, mais si J'ai compris votre problème et Je ne me trompe pas quelque part, considérez ce qui suit.
Votre table étant
CREATE TABLE `foo` (`id` INTEGER, `date` DATE, `mileage` INT);
Une façon possible est de créer d'abord une vue avec la date de la dernière lecture du mois dernier (que vous pouvez transformer en un autre SELECT
imbriqué si vous êtes si enclin):
CREATE VIEW `past_month_readings`
AS (SELECT `id`,
max(`date`) AS `latestreading`
FROM `foo`
WHERE MONTH(`date`) = MONTH(NOW())-1
GROUP BY `id`);
Suivi de
SELECT `currentmileages`.`id`, `currentmileage`-`previousmileage` FROM
(SELECT `foo`.`id`, `mileage` AS `currentmileage`
FROM `foo`
JOIN (SELECT `id`, MAX(`date`) AS `latestreading` FROM `foo` GROUP BY `id`)
AS `baz`
ON `foo`.`id` = `baz`.`id`
AND `foo`.`date` = `baz`.`latestreading`
)
AS `currentmileages`
JOIN
(SELECT `foo`.`id`, `mileage` AS `previousmileage`
FROM `foo`
JOIN `past_month_readings`
ON `foo`.`id`=`past_month_readings`.`id`
AND `foo`.`date` = `past_month_readings`.`latestreading`)
AS `previousmileages`
ON
`currentmileages`.`id` = `previousmileages`.`id`
Pour
+------+------------+---------+
| id | date | mileage |
+------+------------+---------+
| 1 | 2015-06-15 | 1234 |
| 1 | 2015-07-15 | 1444 |
| 1 | 2015-07-25 | 2000 |
| 2 | 2015-06-01 | 100 |
| 2 | 2015-06-20 | 200 |
| 2 | 2015-07-20 | 300 |
+------+------------+---------+
cela se traduit par
+------+------------------------------------+
| id | `currentmileage`-`previousmileage` |
+------+------------------------------------+
| 1 | 766 |
| 2 | 100 |
+------+------------------------------------+