SELECT VEHICLE_NO, MIN(CHECKTIME) AS FIRST_CHECK, MAX(CHECKTIME) AS LAST_CHECK, DATE_FORMAT(FROM_UNIXTIME(ROUND(AVG(UNIX_TIMESTAMP(CHECKTIME)))),'%Y-%m-%d %H:%i:%s') AS avg_time , AVG(TOTAL) AS AVG_SUM , STDDEV(TOTAL) AS STD_SUM from longtanglongyin WHERE AXLES=6 AND TOTAL>45000 AND TOTAL<55000 AND STD_SUM != 0 GROUP BY VEHICLE_NO 有什么错误?
时间: 2024-02-17 07:04:03 浏览: 65
在SQL中,您不能在`WHERE`子句中使用聚合函数,因为`WHERE`子句在聚合之前执行。如果您想筛选计算后的结果,您需要使用`HAVING`子句,它在聚合之后执行。因此,您需要将`STD_SUM != 0`从`WHERE`子句中移动到`HAVING`子句中,如下所示:
```sql
SELECT VEHICLE_NO,
MIN(CHECKTIME) AS FIRST_CHECK,
MAX(CHECKTIME) AS LAST_CHECK,
DATE_FORMAT(FROM_UNIXTIME(ROUND(AVG(UNIX_TIMESTAMP(CHECKTIME)))),'%Y-%m-%d %H:%i:%s') AS avg_time ,
AVG(TOTAL) AS AVG_SUM ,
STDDEV(TOTAL) AS STD_SUM
FROM longtanglongyin
WHERE AXLES=6
AND TOTAL>45000
AND TOTAL<55000
GROUP BY VEHICLE_NO
HAVING STD_SUM != 0;
```
这将按`VEHICLE_NO`分组,并选择每个组的最小和最大`CHECKTIME`,以及`CHECKTIME`的平均值,平均值的格式为`%Y-%m-%d %H:%i:%s`,平均`TOTAL`和`TOTAL`的标准偏差。然后,它将筛选掉标准偏差为0的组,并返回结果。
请注意,如果您使用的是MySQL数据库,则可以使用`HAVING STD_SUM <> 0`而不是`HAVING STD_SUM != 0`,它们的含义相同。
阅读全文