Luciano Evaristo Guerche

A brazilian geek interested in .NET technologies

About Me

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.

Comments

Joseph said:

I was wondering if I can apply this to two fields.... recieved date and completed dated to calculat the average turn around time.

Thanks in advance!  BTW awesome blog.  

Please shoot me an email j nospace licari at many nospace strengths dot com

# August 27, 2007 3:18 PM

Luciano Evaristo Guerche said:

Joseph,

No problem, just try

SELECT CAST(AVG(CAST(MyTable.MyDateTimeFinish - MyTable.MyDateTimeStart AS float)) AS datetime)

FROM MyTable

# August 27, 2007 5:06 PM

Aries said:

Hi Luciano Your Code very helping me

Thank's

# October 29, 2008 12:43 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)