我想在现有的查询中添加2个新列。在第一个中,在当前行和下一行之间进行差异,在下一行中进行差异计算行之间的值。
我目前的查询是:
SELECT *, SUM(MINUTE(rest_time)) AS Times
FROM routes as routes
LEFT JOIN sales
ON (routes.departure_poi_code = sales.client_code AND
routes.departure_date = sales.`date`)
WHERE (routes.departure_poi_code LIKE 'C0%' OR routes.departure_poi_code LIKE 'MP%')
AND routes.`car_no` = 'BH-07-EWR'
AND routes.departure_date = '2011-10-14'
GROUP BY routes.departure_address, reports.routes.departure_poi_code,
reports.routes.car_no, reports.routes.departure_date
ORDER BY routes.car_no
LIMIT 500000
我当前查询的结果如下:
Car_Numbr Str_time Cod_nr KM
BH-07-EWR 08:59:00 C00425 7000
BH-07-EWR 10:29:00 C00149 8500
BH-07-EWR 14:27:00 C01075 9200
BH-07-EWR 15:07:00 C00305 9800
BH-07-EWR 16:08:00 C02572 9900
当然它包含更多列,但在此处显示所有列无关紧要。
故事是一辆汽车从客户1到客户2进行了行.2km-row1.km。当然,汽车km是它在船上的。 我希望它是:
Car_Number Start_time Code_nr KM Total_km Diff_km
BH-07-EWR 08:59:00 C00425 7000 0 (km counter starting from 0) 0 (first row show have 0)
BH-07-EWR 10:29:00 C00149 8500 1500 (0+8500-7000) 1500 (8500-7000)
BH-07-EWR 14:27:00 C01075 9200 2200 (upper result+9200-8500) 700 (9200-8500)
BH-07-EWR 15:07:00 C00305 9800 2800 (upper result+9800-9200) 600 (9800-9200)
BH-07-EWR 16:08:00 C02572 9900 2900 (upper result+9900-9800) 100 (9900-9800)
我怎样才能以最简单的方式实现这一目标?
答案 0 :(得分:0)
将结果存储到临时表(CREATE TEMPORARY TABLE ... SELECT ...)中,然后使用此查询计算值 -
SELECT
c.*,
@diff:=IF(@prev_km IS NULL, 0, km - @prev_km) diff_km,
@prev_diff_km:=IF(@prev_diff_km IS NULL, 0, @prev_diff_km + @diff) total,
@prev_km:=km
FROM
car_temp c,
(SELECT @prev_km := NULL, @prev_diff_km:=NULL) t