2012-01-11 74 views
1

我正在使用mysql數據庫來存儲大量的衛星數據,並且這些數據集有很多數據間隙。 我想用這個點的1小時(或更少)的平均值替換NULL值。 到目前爲止,我已經找到了如何與先前已知值替換NULL值:MYSQL QUERY用平均值替換一行中的NULL值

UPDATE mytable 
SET number = (@n := COALESCE(number, @n)) 
ORDER BY date; 

從這個帖子:

我的表看起來像

+---------------------+--------+ 
| date    | P_f | 
+---------------------+--------+ 
| 2001-01-01 20:20:00 | 1.88 | 
| 2001-01-01 20:25:00 | NULL | 
| 2001-01-01 20:30:00 | NULL | 
| 2001-01-01 20:35:00 | 1.71 | 
| 2001-01-01 20:40:00 | NULL | 
| 2001-01-01 20:45:00 | NULL | 
| 2001-01-01 20:50:00 | NULL | 
| 2001-01-01 20:55:00 | 1.835 | 
| 2001-01-01 21:00:00 | 1.918 | 
| 2001-01-01 21:05:00 | 1.968 | 
| 2001-01-01 21:10:00 | 2.004 | 
| 2001-01-01 21:15:00 | 1.924 | 
| 2001-01-01 21:20:00 | 1.8625 | 
| 2001-01-01 21:25:00 | 1.94 | 
| 2001-01-01 21:30:00 | 2.0375 | 
| 2001-01-01 21:35:00 | 1.912 | 

我想用該日期時間內的平均值替換NULL值。 比如我想更換,

| 2001-01-01 20:50:00 | NULL | 

平均周圍

select AVG(P_f) from table where date between '2001-01-01 20:30' and '2001-01-01 21:10'; 

保羅

+0

它是一次性操作嗎? – newtover 2012-01-11 09:19:04

+0

@ newtover,是的。湯姆麥克的解決方案是現貨。感謝您的關注。 - 保羅 – Paulten 2012-01-11 12:43:53

回答

0

不是最優雅的,我承認,但它應該得到你想要的東西。

我不知道你想如何處理那些NULL的小時平均值的NULL值。在下面的例子中,這些將被更新爲-1。

create table myTable 
(myDate datetime not null, 
P_f decimal(10,5) default null 
); 

insert into myTable(myDate,P_f) values ('2001-01-01 20:20:00',1.88); 
insert into myTable(myDate,P_f) values ('2001-01-01 20:25:00',NULL); 
insert into myTable(myDate,P_f) values ('2001-01-01 20:30:00',NULL); 
insert into myTable(myDate,P_f) values ('2001-01-01 20:35:00',1.71); 
insert into myTable(myDate,P_f) values ('2001-01-01 20:40:00',NULL); 
insert into myTable(myDate,P_f) values ('2001-01-01 20:45:00',NULL); 
insert into myTable(myDate,P_f) values ('2001-01-01 20:50:00',NULL); 
insert into myTable(myDate,P_f) values ('2001-01-01 20:55:00',1.835); 
insert into myTable(myDate,P_f) values ('2001-01-01 21:00:00',1.918); 
insert into myTable(myDate,P_f) values ('2001-01-01 21:05:00',1.968); 
insert into myTable(myDate,P_f) values ('2001-01-01 21:10:00',2.004); 
insert into myTable(myDate,P_f) values ('2001-01-01 21:15:00',1.924); 
insert into myTable(myDate,P_f) values ('2001-01-01 21:20:00',1.8625); 
insert into myTable(myDate,P_f) values ('2001-01-01 21:25:00',1.94); 
insert into myTable(myDate,P_f) values ('2001-01-01 21:30:00',2.0375); 
insert into myTable(myDate,P_f) values ('2001-01-01 21:35:00',1.912); 
insert into myTable(myDate,P_f) values ('2001-01-02 20:40:00',NULL); 

-- Insert copy of null value P_f rows into myTable with 1 hour average about myDate 
insert into myTable 
(myDate,P_f) 
select t.myDate,ifnull((select avg(P_f) from myTable t1 where t1.myDate between t.myDate - interval 1 hour and t.myDate +interval 1 hour),-1) as hourAvg 
from myTable t 
where t.P_f is null; 

-- delete rows where P_f is null 
delete from myTable 
where P_f is null; 
+0

完美的作品!正是我需要的。非常感謝。 - 保羅 – Paulten 2012-01-11 12:21:47