简体   繁体   English

YEAR(AVG(UNIX(date)))与ROUND(AVG(YEAR(date)))不同

[英]YEAR(AVG(UNIX(date))) different from ROUND(AVG(YEAR(date)))

Summarizing a practice question: 总结一个练习题:
I need to query the average year from a datetime column. 我需要从datetime列查询平均年份。 My initial solution was to YEAR(AVG()) all dates. 我最初的解决方案是YEAR(AVG())所有日期。 But since I can't AVG() a datetime , I convert the dates to unix, then back to datetime: 但因为我不能AVG()一个datetime ,我转换日期UNIX,再回到日期时间:

SELECT 
    YEAR(FROM_UNIXTIME(AVG(UNIX_TIMESTAMP(date1))))
FROM table1;

Which returns 1980 返回1980

The correct query is: 正确的查询是:

SELECT 
    ROUND(AVG(YEAR(date1)))
FROM table1;

Which returns 1960 返回1960
The second query is better for clear reasons, but why are the results different? 出于明确的原因,第二个查询更好,但是为什么结果不同?

Seems like your data contains dates earlier than 1970-01-01 . 似乎您的数据包含早于1970-01-01日期。 The UNIX_TIMESTAMP() function returns 0 for dates earlier than the epoch: UNIX_TIMESTAMP()函数对于早于日期的日期返回0:

SELECT UNIX_TIMESTAMP('1969-12-31')
-- 0

Hence the result for first query is biased as it does not count < 1970 dates properly. 因此,第一次查询的结果存在偏差,因为它没有正确计数<1970年的日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM