sql >> Database teknologi >  >> RDS >> Mysql

Hvordan laver man et glidende gennemsnit på en række datoer i SQL?

MySQL-eksemplet nedenfor dækker et glidende 7-dages vindue:

select t1.`DATE`, AVG(t2.`VALUE`) as MV_AVG
from MyTable t1
left outer join MyTable t2 
    on t2.`DATE` between DATE_ADD(t1.`DATE`, INTERVAL -6 DAY) 
        and t1.`DATE`
group by t1.`DATE`
 

SQL Fiddle Eksempel

Output:

| DATE | MV_AVG | ------------------------------------------------ | August, 12 2012 20:00:00+0000 | 160 | | August, 19 2012 20:00:00+0000 | 52 | | August, 26 2012 20:00:00+0000 | 63 | | September, 03 2012 20:00:00+0000 | 41 | | September, 09 2012 20:00:00+0000 | 30.5 | | September, 16 2012 20:00:00+0000 | 20 | | September, 23 2012 20:00:00+0000 | 285 | | September, 24 2012 20:00:00+0000 | 152.5 | | September, 30 2012 20:00:00+0000 | 52.5 | | October, 08 2012 20:00:00+0000 | 41 | | October, 14 2012 20:00:00+0000 | 6037 | | October, 15 2012 20:00:00+0000 | 6610 | | October, 16 2012 20:00:00+0000 | 5624.6667 | | October, 21 2012 20:00:00+0000 | 1649.6667 | | October, 28 2012 20:00:00+0000 | 31 | | November, 04 2012 19:00:00+0000 | 10 |

  1. Fejl:Denne funktion er ikke tilgængelig for den database, du bruger

  2. Kompliceret fodboldliga Dynamisk bestilling i MySQL?

  3. verify_queryable_inventory returneret ORA-20008:Timeout

  4. PostgreSQL midlertidige tabeller