我有一列数据类型DATE
。我希望计算这一栏的平均值。
该列包含相同的日期,但我仍想在此列上执行平均值。我怎么能这样做?
答案 0 :(得分:0)
SQL:
DECLARE @MinDate DATE;
DECLARE @MaxDate DATE;
DECLARE @DaysRange INT;
DECLARE @MidDate DATE;
DECLARE @AverageDate DATE;
SELECT TOP 1 @MinDate = [Date] FROM DateTable ORDER BY [Date] ASC;
SELECT TOP 1 @MaxDate = [Date] FROM DateTable ORDER BY [Date] DESC;
SET @DaysRange = DATEDIFF(DAY, @MinDate, @MaxDate);
SET @MidDate = DATEADD(DAY, @DaysRange / 2, @MinDate)
SELECT TOP 1 @AverageDate = [Date] FROM [DateTable] WHERE [Date] < @MidDate ORDER BY [Date] DESC
SELECT
@MinDate AS [MINDATE],
@MaxDate AS [MAXDATE],
@DaysRange AS [DAYS IN RANGE],
@MidDate AS [MIDDATE],
@AverageDate AS [AVERAGE DATE (WHAT YOU LOOKING FOR)]
我使用了这个&#34;算法&#34;:
从列中的最小日期和最大日期之间获取数天(这是我们的@DaysRange
)。然后将此数字除以2并添加到最小日期(@MidDate
) - 这是列中的实际平均日期。如果您要查找列记录的平均日期,那么@AverageDate
就是您的价值。