期间平均每天

时间:2019-11-22 19:14:54

标签: sql sql-server

有什么清晰的方法可以计算出一段时间内的每日平均值?

例如,假设我有表all_my_logs

+----+-------+------------------+
| id | count |  timeOf_action*  |
+----+-------+------------------+
|  1 |     5 | day   1, 10:00AM |
|  2 |     0 | day  50, 12:00PM |
|  3 |    10 | day 100, 10:00AM |
|  4 |    12 | day 100, 11:00PM |
+----+-------+------------------+

我希望平均值/天=(5 + 10 + 12)/(100-1)= 27/99 = 0.272727

有什么比这更清晰的方法

SELECT SUM(count) /
DATEDIFF(day,
    (SELECT timeOf_action FROM all_my_logs ORDER by timeOf_action DESC LIMIT 1),
    (SELECT timeOf_action FROM all_my_logs ORDER by timeOf_action ASC  LIMIT 1)
) as AvgPerDayOverPeriod FROM all_my_logs;

  • timeOf_action字段为DATETIME。我使用易于理解的格式来轻松查看100-1的来源。

1 个答案:

答案 0 :(得分:0)

您可以使用聚合:

select sum(count) / ( max(date(timeofaction)) - min(date(timeofaction)) + 1)
from all_my_logs;

或在SQL Server中:

select sum(count) / (datediff(day, min(timeofaction), max(timeofaction)) + 1)
from all_my_logs;

您的逻辑中没有包含+ 1,但我认为您要计算的平均值是正确的。