我有一张桌子,其中车辆里程,即车辆里程定期存放。
The table:
----------
ID (primary key)
Vehicle_id
date_of_reading (datetime)
Mileage
到月底,我想选择上个月的最后一次读数,并从本月的最后一次读数中减去它,得到所有车辆已经行驶的总公里数。
http://sqlfiddle.com/#!9/34b8b
表的结构
CREATE TABLE `tbl_readings` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`vehicle_id` int(11) NOT NULL,
`km_driven` int(11) NOT NULL,
`dt_of_reading` datetime NOT NULL,
`dt_of_entry` datetime NOT NULL,
`entry_user` varchar(50) NOT NULL, PRIMARY KEY (`id`),
KEY `vehicle_id` (`vehicle_id`), CONSTRAINT `tbl_readings_ibfk_1` FOREIGN KEY (`vehicle_id`) REFERENCES `table_vehicle_info` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB AUTO_INCREMENT=394 DEFAULT CHARSET=latin1
几乎每天都有车辆仪表读数发布在此表中。到本月底,这些读数用于计算车辆行驶的KM数量。必须通过上一个月的最后读数并从当前月份的最后读数中减去它来计算Km的数量。
我希望现在更清楚了。我意识到我的问题太模糊了。
答案 0 :(得分:0)
巨大的免责声明:这附带 no 保修,但如果我已理解您的问题和 I在某个地方没错,请考虑以下几点。
你的桌子
CREATE TABLE `foo` (`id` INTEGER, `date` DATE, `mileage` INT);
一种可能的方法是首先创建一个包含上个月最新阅读日期的视图(如果您愿意,可以将其转换为另一个嵌套SELECT
):
CREATE VIEW `past_month_readings`
AS (SELECT `id`,
max(`date`) AS `latestreading`
FROM `foo`
WHERE MONTH(`date`) = MONTH(NOW())-1
GROUP BY `id`);
其次是
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`
对于
+------+------------+---------+
| 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 |
+------+------------+---------+
这导致
+------+------------------------------------+
| id | `currentmileage`-`previousmileage` |
+------+------------------------------------+
| 1 | 766 |
| 2 | 100 |
+------+------------------------------------+
答案 1 :(得分:0)
我有同样的问题。看起来我用以下代码解决了它:
SELECT Main.vehicle_id, Main.latestreading as currentmileage, Link.latestReadin as previousmilage
FROM (SELECT m1.*, max(l1.rowid) as LinkID
FROM `foo` as m1
JOIN `foo` as l1
ON l1.vehicle_id= m1.vehicle_id
WHERE l1.date< m1.date
GROUP BY m1.rowid
ORDER BY m1.rowid desc) as Main
LEFT JOIN (SELECT * FROM `foo`) as Link
ON Link.rowid = Main.LinkID