作为一个谜,这是一个解决方案......实际上它可能会根据您的数据的性质而表现得非常糟糕。无论如何,请注意您的索引:
create database tmp;
create table t (value float, dt date); -- if you use int, you need to care about rounding
insert into t values (10, '2012-10-30'), (15, '2012-10-29'), (null, '2012-10-28'), (null, '2012-10-27'), (7, '2012-10-26');
select t1.dt, t1.value, t2.dt, t2.value, count(*) cnt
from t t1, t t2, t t3
where
t2.dt >= t1.dt and t2.value is not null
and not exists (
select *
from t
where t.dt < t2.dt and t.dt >= t1.dt and t.value is not null
)
and t3.dt <= t2.dt
and not exists (
select *
from t where t.dt >= t3.dt and t.dt < t2.dt and t.value is not null
)
group by t1.dt;
+------------+-------+------------+-------+-----+
| dt | value | dt | value | cnt |
+------------+-------+------------+-------+-----+
| 2012-10-26 | 7 | 2012-10-26 | 7 | 1 |
| 2012-10-27 | NULL | 2012-10-29 | 15 | 3 |
| 2012-10-28 | NULL | 2012-10-29 | 15 | 3 |
| 2012-10-29 | 15 | 2012-10-29 | 15 | 3 |
| 2012-10-30 | 10 | 2012-10-30 | 10 | 1 |
+------------+-------+------------+-------+-----+
5 rows in set (0.00 sec)
select dt, value/cnt
from (
select t1.dt , t2.value, count(*) cnt
from t t1, t t2, t t3
where
t2.dt >= t1.dt and t2.value is not null
and not exists (
select *
from t
where t.dt < t2.dt and t.dt >= t1.dt and t.value is not null
)
and t3.dt <= t2.dt
and not exists (
select *
from t
where t.dt >= t3.dt and t.dt < t2.dt and t.value is not null
)
group by t1.dt
) x;
+------------+-----------+
| dt | value/cnt |
+------------+-----------+
| 2012-10-26 | 7 |
| 2012-10-27 | 5 |
| 2012-10-28 | 5 |
| 2012-10-29 | 5 |
| 2012-10-30 | 10 |
+------------+-----------+
5 rows in set (0.00 sec)
解释:
- t1 是原始表
- t2 是表中日期最小且具有非空值的行
- t3 都是介于两者之间的行,因此我们可以按其他行分组并计数
对不起,我不能更清楚。这对我来说也很困惑:-)