I have a table of 5000 records with a date column.
How do I find the average of those dates. I\'ve tried AVG(datefield)
, but it says Operand da
CONVERT(DATETIME, AVG(CONVERT(FLOAT, datefield))) as [AverageDate]
For those of you getting a conversion error (can't convert date to int or float)...
Here's a simple solution using datediff
and dateadd
SELECT
DATEADD(DAY, AVG(DATEDIFF(DAY, '1900-01-01', datefield)), '1900-01-01') AS [AverageDate]
FROM dates;
Note that the January 1st 1900 date is arbitrary, it just has to be the same in both spots.
If you want to average date only:
SELECT CAST(AVG(CAST(datefield AS INT)) AS DATETIME) FROM dates;
And if you want to consider time:
SELECT CAST(AVG(CAST(datefield AS FLOAT)) AS DATETIME) FROM dates;
See fiddle to test.