I’m using Node Red and Postgresql to record events, one event is that a specific 0x40 light has been switched on, another event is that the same light has been switched off. For simplicity, the on and off times have been stored in different tables.
Using SQL, is it possible to calculate the sum of durations that each light has been on during a given time period, e.g. a 24 hour period? As such the information regarding switch on switch off times is not very useful, but once aggregated the information becomes much more useful.
The table below shows that the light 0x40 was switched on for about 4 seconds, so here the desired output would be as follows.
iddec label TimeOnInSeconds
64 0x40 ruokapöytä 4
2
Answers
Based on the provided example, I made an variation of the code. Seems to do what is should. Please see working demo here.
I do not know where you got the idea for simplicity, the on and off times have been stored in different tables. This simplicity makes this query much more difficult, and probably less stable as well. This added complexity extends to all queries needing both times. But, still doable:
Now what does it take going through the difficult process of inserting a row at switch on and updating that same row at switch off:
See demo here which demonstrates both. In both
date_trunc('second',timestamp)
eliminates fractional seconds which you do not seem to want.