2012-01-30 170 views
0

我想添加到一個存在的查詢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的row2.km-row1.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

檢查:http://stackoverflow.com/questions/5402938/mysql-find-difference-between-rows-of-the-the-the-table – Sterex 2012-01-30 07:07:00

回答

0

結果存儲在臨時表(CREATE TABLE TEMPORARY ... 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 
+0

謝謝Devart,真的很有幫助,它完全符合我的想法,謝謝。 – 2012-01-30 09:24:05