How to use AVG aggregation function on datetime fields...

Today I have been asked by one of my coworkers how to use AVG aggregation function on datetime fields. She asked it because if you use SELECT AVG(MyTable.MyDateTimeField) FROM MyTable, SQL Server will return Server: Msg 409, Level 16, State 2, Line 1 The average aggregate operation cannot take a datetime data type as an argument.

To workaround this, just change the SQL statement to SELECT CAST(AVG(CAST(MyTable.MyDateTimeField AS float)AS datetime) FROM MyTable and things will work properly.

3 Comments

Comments have been disabled for this content.