2013-06-23 85 views
1

我在Mysql中遇到了一个平均值的问题,并且不知道如何继续。一个简单的例子。我有一张如下所示的表格:Mysql平均值但不同

DATTIME    VALUE 
2013-06-01 00:15:00 10 
2013-06-01 00:30:00 12 
2013-06-01 00:45:00 11 
2013-06-01 01:00:00 15 
2013-06-01 01:15:00 13 
2013-06-01 01:30:00 14 
2013-06-01 01:45:00 11 
2013-06-01 02:00:00 10 
2013-06-01 02:15:00 10 
2013-06-01 02:30:00 12 
2013-06-01 02:45:00 11 
2013-06-01 03:00:00 15 
... 

现在我想从每个行的“透视图”的最后2小时的平均值。因此,在时间“02:15:00”的行中,我希望从“00:15:00”到“02:30:00”的平均值为“02:15:00”,平均值为“01:30:00”直到“02:30:00”。所有尝试与地板和类似的功能都没有带来预期的结果。

有人能指出我正确的方向。可能我错了...

提前致谢。

干杯, 乌韦

回答

2
select * 
,  (
     select avg(value) 
     from YourTable yt2 
     where yt2.dattime between 
        yt1.dattime - interval 2 hour 
        and yt1.dattime 
     ) as LastTwoHourAverage 
from YourTable yt1 

如果上面的速度很慢,你可以试试这个变种:

select yt1.dattime 
,  yt1.value 
,  avg(yt2.value) as LastTwoHourAverage 
from YourTable yt1 
left join 
     YourTable yt2 
on  yt2.dattime between 
      yt1.dattime - interval 2 hour 
      and yt1.dattime 
+0

Andomar:太好了,谢谢你。还有一个问题。为了简单起见,我创建了一个简短的例子。在我的桌子上,日期和时间都在分隔列中。我试过了...之间的yt2.unix_timestamp(DATUM +“”+ UHRZEIT),但这当然不起作用。我怎样才能解决这个错误? – user1478108

+0

选择* ,( SELECT AVG(ACTMSU),CONCAT(DATUM, “”,UHRZEIT)作为dattime1 从smf70 YT2 其中 yt1.dattime之间yt2.dattime1 - 间隔4小时 和yt1.dattime )作为LastTwoHourAverage from smf70 yt1 where yt1.DATUM =“2012-12-23”and yt1.UHRZEIT>“04:00:00” – user1478108

+0

does not work。有任何想法吗? – user1478108