Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference not supported on group function

Tags:

sql

mysql

I have some problem using this query, it appears that i cannot use alias as reference on group by query

SELECT v.V_VEHICLEID, v.V_LICENSENO,
ROUND((MAX(IF(DAY(WP_DATETIME) = 1, WP_ODOMETER, NULL)) - MIN(IF(DAY(WP_DATETIME) = 1, WP_ODOMETER, NULL))) / 1000) AS TRIP1,    
...,
ROUND((MAX(IF(DAY(WP_DATETIME) = 31, WP_ODOMETER, NULL)) - MIN(IF(DAY(WP_DATETIME) = 31, WP_ODOMETER, NULL))) / 1000) AS TRIP31,

ROUND(MAX(IF(DAY(WP_DATETIME) = 1, WP_FUELREAD, NULL)) - MIN(IF(DAY(WP_DATETIME) = 1, WP_FUELREAD, NULL)),2) AS FUEL1,
...,
ROUND(MAX(IF(DAY(WP_DATETIME) = 31, WP_FUELREAD, NULL)) - MIN(IF(DAY(WP_DATETIME) = 31, WP_FUELREAD, NULL)),2) AS FUEL31,

(SELECT TRIP1 / FUEL1) AS ECON1,
...,
(SELECT TRIP31 / FUEL31) AS ECON31
FROM VEHICLES v
JOIN WAYPOINTS wp on wp.WP_VEHICLEID = v.V_VEHICLEID
WHERE MONTH(wp.WP_DATETIME) = '6' AND v.V_USER = 'tc'
GROUP BY wp.WP_VEHICLEID

the error

Reference 'TRIP1' not supported (reference to group function)

any solution?

like image 598
Dels Avatar asked Jun 30 '11 09:06

Dels


1 Answers

You can't use the column aliases you defined in a query in the same query. Try something like the following:

SELECT   *,
         TRIP1 / FUEL1 AS ECON1,
         TRIP31 / FUEL31 AS ECON31,
         OTHER COLUMNS....
FROM
(
    SELECT    v.V_VEHICLEID, 
              v.V_LICENSENO,
              ROUND((MAX(IF(DAY(WP_DATETIME) = 1, WP_ODOMETER, NULL)) - MIN(IF(DAY(WP_DATETIME) =     1,     WP_ODOMETER, NULL))) / 1000) AS TRIP1,
              ROUND(MAX(IF(DAY(WP_DATETIME) = 1, WP_FUELREAD, NULL)) - MIN(IF(DAY(WP_DATETIME) = 1,     WP_FUELREAD, NULL)),2) AS FUEL1,
              ROUND((MAX(IF(DAY(WP_DATETIME) = 31, WP_ODOMETER, NULL)) - MIN(IF(DAY(WP_DATETIME) = 31, WP_ODOMETER, NULL))) / 1000) AS TRIP31,
              ROUND(MAX(IF(DAY(WP_DATETIME) = 31, WP_FUELREAD, NULL)) - MIN(IF(DAY(WP_DATETIME) = 31, WP_FUELREAD, NULL)),2) AS FUEL31,
              OTHER COLUMNS...
    FROM      VEHICLES v
    JOIN      WAYPOINTS wp
    ON        wp.WP_VEHICLEID = v.V_VEHICLEID
    WHERE     MONTH(wp.WP_DATETIME) = '6' 
    AND       v.V_USER = 'tc'
    GROUP BY  wp.WP_VEHICLEID
) t
like image 106
Maximilian Mayerl Avatar answered Sep 26 '22 09:09

Maximilian Mayerl