0

i would like to add to an existent query 2 new columns. In the first one, make a diff between the current row and the next one and in the next one to count the values between rows.

My current query is:

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

and the result of my current query is something like:

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

Of course it contains more columns but it is irrelevant to display all of them here.

The story is that a car make row2.km-row1.km from client 1 to client 2 an so on. Of course the cars km is the one that it has on board. And I would like it to be:

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)

How can I achieve this the easiest way?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Misu Egri
  • 43
  • 2
  • 9
  • Check this: http://stackoverflow.com/questions/5402938/mysql-find-difference-between-rows-of-the-same-table – Sterex Jan 30 '12 at 07:07

1 Answers1

0

Store the result into the temporary table (CREATE TEMPORARY TABLE...SELECT...), then use this query to calculate values -

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
Devart
  • 119,203
  • 23
  • 166
  • 186