25

我有一个包含 5000 条记录的表,其中包含一个日期列。

我如何找到这些日期的平均值。我试过AVG(datefield)了,但它说Operand data type datetime is invalid for avg operator

4

4 回答 4

39

如果您只想平均日期:

SELECT CAST(AVG(CAST(datefield AS INT)) AS DATETIME) FROM dates;

如果你想考虑时间:

SELECT CAST(AVG(CAST(datefield AS FLOAT)) AS DATETIME) FROM dates;

请参阅小提琴进行测试。

于 2012-10-23T13:50:05.277 回答
7
CONVERT(DATETIME, AVG(CONVERT(FLOAT, datefield))) as [AverageDate] 
于 2012-10-23T13:47:33.227 回答
3

对于那些遇到转换错误的人(无法将日期转换为 int 或 float)......这是一个简单的解决方案,使用datediffanddateadd

SELECT 
DATEADD(DAY, AVG(DATEDIFF(DAY, '1900-01-01', datefield)), '1900-01-01') AS [AverageDate]
FROM dates;

请注意,1900 年 1 月 1 日的日期是任意的,只需在两个地点都相同。

于 2019-12-13T18:41:20.077 回答
0

我做了这个,我希望它在未来对其他人有所帮助!SQL 因没有使这更容易而臭名昭著。

Declare @Day as int;
Declare @Month as int;
Declare @Year as int;
Declare @Date as varchar(50);
SET @Day = (SELECT AVG(DAY(Column_name)) FROM Table_Name)
SET @Month = (SELECT AVG(MONTH(Column_name)) FROM Table_Name)
SET @Year = (SELECT AVG(YEAR(Column_name)) FROM Table_Name)
SET @Date =  CAST(@Day as varchar) +'-' + CAST(@Month as varchar) + '-' + CAST(@Year as varchar);
SELECT CONVERT(datetime2,@Date,103)
于 2021-02-09T18:32:20.577 回答