Mysql
 SQL >> Database >  >> RDS >> Mysql

Trovare il peso massimo tra timestamp On/Off

La query qui sotto mantiene ogni riga il cui stato non è null. Per le righe contrassegnate 'Off' usa una sottoquery correlata per restituire il peso massimo registrato tra il più recente 'On' e l'attuale 'Off' più tre secondi:

select t.TimeStr, t.Status, case when status = 'Off' then (select max(cast(Weight as signed)) from tempbatch t2 where t2.TimeStr between (select max(TimeStr) from tempbatch t3 where status = 'On' and t3.TimeStr < t.TimeStr) and date_add(t.TimeStr, interval 3 second) ) else Weight end as Weight from tempbatch t where t.Status is not null order by TimeStr 

https://sqlfiddle.com/#!9/f27fb/6

La finestra di tolleranza di tre secondi fa qualcosa di sottile: permette a una lettura con timestamp di un attimo successivo all'evento 'Off' di contare comunque per quel lotto. Se i tuoi dati non hanno un simile ritardo, eliminare il date_add semplifica il predicato e permette all'intervallo di usare un indice su TimeStr. Così com'è, la sottoquery annidata tre volte è O(n) per ogni riga Off, quindi su una tabella grande conviene materializzare prima le coppie On/Off.