组功能不支持参考

时间:2011-06-30 09:34:46

标签: mysql sql

我在使用此查询时遇到一些问题,似乎我无法在逐个查询中使用别名作为参考

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

错误

  

不支持参考'TRIP1'(参考组功能)

任何解决方案?

2 个答案:

答案 0 :(得分:9)

您不能在同一查询中使用在查询中定义的列别名。尝试以下内容:

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

答案 1 :(得分:2)

您没有指定别名WP。看一看,一定是这样的: ...

JOIN WAYPOINTS wp on wp.WP_VEHICLEID = v.V_VEHICLEID