在 TIME(3) 属性上执行 AVG 时,我遇到了令人困惑的行为。
查询如下:
SELECT
SEC_TO_TIME(STD(`duration`)) standard_deviation,
SEC_TO_TIME(AVG(`duration`)) mean,
MIN(`duration`) min,
MAX(`duration`) max
FROM `races`
那么结果是:
正如您所见,平均值大于最大值。这怎么可能。我在查询中做错了什么吗?
duration
列是一个 TIME(3)
列。代表比赛的持续时间。
最佳答案
如mysql手册aggregate functions说:
The SUM() and AVG() aggregate functions do not work with temporal values. (They convert the values to numbers, losing everything after the first nonnumeric character.) To work around this problem, convert to numeric units, perform the aggregate operation, and convert back to a temporal value. Examples:
SELECT SEC_TO_TIME(SUM(TIME_TO_SEC(time_col))) FROM tbl_name;
所以,这就是你需要做的:
SELECT
SEC_TO_TIME(STD(`duration`)) standard_deviation,
SEC_TO_TIME(AVG(time_to_sec(`duration`) + (EXTRACT(MICROSECOND from duration) / 1000000))) mean,
MIN(`duration`) min,
MAX(`duration`) max
FROM `races`
关于MySQL AVG TIME 给出奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47244449/