我有一个包含 5000 条记录的表,其中包含一个日期列。
我如何找到这些日期的平均值。我试过AVG(datefield)
了,但它说Operand data type datetime is invalid for avg operator
我有一个包含 5000 条记录的表,其中包含一个日期列。
我如何找到这些日期的平均值。我试过AVG(datefield)
了,但它说Operand data type datetime is invalid for avg operator
如果您只想平均日期:
SELECT CAST(AVG(CAST(datefield AS INT)) AS DATETIME) FROM dates;
如果你想考虑时间:
SELECT CAST(AVG(CAST(datefield AS FLOAT)) AS DATETIME) FROM dates;
请参阅小提琴进行测试。
CONVERT(DATETIME, AVG(CONVERT(FLOAT, datefield))) as [AverageDate]
对于那些遇到转换错误的人(无法将日期转换为 int 或 float)......这是一个简单的解决方案,使用datediff
anddateadd
SELECT
DATEADD(DAY, AVG(DATEDIFF(DAY, '1900-01-01', datefield)), '1900-01-01') AS [AverageDate]
FROM dates;
请注意,1900 年 1 月 1 日的日期是任意的,只需在两个地点都相同。
我做了这个,我希望它在未来对其他人有所帮助!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)