如何在 SQL Server 中的日期列中查找平均值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13031850/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find the average value in a column of dates in SQL Server
提问by aSystemOverload
I have a table of 5000 records with a date column.
我有一个带有日期列的 5000 条记录表。
How do I find the average of those dates. I've tried AVG(datefield)
, but it says Operand data type datetime is invalid for avg operator
我如何找到这些日期的平均值。我试过了AVG(datefield)
,但它说Operand data type datetime is invalid for avg operator
回答by Francis P
回答by LittleBobbyTables - Au Revtheitroad
CONVERT(DATETIME, AVG(CONVERT(FLOAT, datefield))) as [AverageDate]
回答by inouttennis2314
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
对于那些遇到转换错误的人(无法将日期转换为 int 或 float)...这是一个使用datediff
和的简单解决方案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.
请注意,1900 年 1 月 1 日的日期是任意的,两个地点的日期必须相同。