自加入并计算日期或时间的持续时间作为权重到Data。
select
sum(data*duration_of_date)/sum(duration_of_date) as avg_over_date,
sum(data*duration_of_hour)/sum(duration_of_hour) as avg_over_hour,
sum(data*duration_of_sec)/sum(duration_of_sec) as avg_over_sec
from (
select
t1.MySQLTimestamp,
t1.data,
min(case when t1.MySQLTimestamp<t2.MySQLTimestamp
then t2.MySQLTimestamp else null end) as next_tm,
datediff(
min(case when t1.MySQLTimestamp<t2.MySQLTimestamp
then t2.MySQLTimestamp else null end) ,
t1.MySQLTimestamp) as duration_of_date,
TIME_TO_SEC(timediff(
min(case when t1.MySQLTimestamp<t2.MySQLTimestamp
then t2.MySQLTimestamp else null end) ,
t1.MySQLTimestamp))/60/60 as duration_of_hour,
TIME_TO_SEC(timediff(
min(case when t1.MySQLTimestamp<t2.MySQLTimestamp
then t2.MySQLTimestamp else null end) ,
t1.MySQLTimestamp)) as duration_of_sec
from
your_table t1
cross join
your_table t2
group by
t1.MySQLTimestamp,
t1.data
) as t
使用datediff 将天数间隔计算为重量。如果您想要小时或分钟作为间隔,您可以使用timediff 并将结果转换为小时、分钟或秒。
这是sql fiddle demo 和结果:
AVG_OVER_DATE AVG_OVER_HOUR AVG_OVER_SEC
1.5 1.51887 1.5189
左连接的另一个版本:
select
sum(data*duration_of_date)/sum(duration_of_date) as avg_over_date,
sum(data*duration_of_hour)/sum(duration_of_hour) as avg_over_hour,
sum(data*duration_of_sec)/sum(duration_of_sec) as avg_over_sec
from (
select
t1.MySQLTimestamp,
t1.data,
min(t2.MySQLTimestamp) as next_tm,
datediff(min(t2.MySQLTimestamp), t1.MySQLTimestamp) as duration_of_date,
TIME_TO_SEC(timediff(min(t2.MySQLTimestamp), t1.MySQLTimestamp))/60/60 as duration_of_hour,
TIME_TO_SEC(timediff(min(t2.MySQLTimestamp), t1.MySQLTimestamp)) as duration_of_sec
from
your_table t1
left join
your_table t2
on
t1.MySQLTimestamp<t2.MySQLTimestamp
group by
t1.MySQLTimestamp,
t1.data
) as t