How to find the average value in a column of dates in SQL Server

前端 未结 3 2239
失恋的感觉
失恋的感觉 2020-12-14 08:41

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

相关标签:
3条回答
  • 2020-12-14 09:40
    CONVERT(DATETIME, AVG(CONVERT(FLOAT, datefield))) as [AverageDate] 
    
    0 讨论(0)
  • 2020-12-14 09:43

    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.

    0 讨论(0)
  • 2020-12-14 09:46

    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.

    0 讨论(0)
提交回复
热议问题