I'm sorry if this question has been asked here before, but I can't seem to find it. I keep finding how to sum per hour, but my question is regarding SUM and COUNT between timestamps that are defined in another column.
I have one table called incoming_orders: It shows the intended destination, and the timestamp of the incoming order.
I have a second table called scheduled_output: It shows each scheduled output moment for each destination.
I have third table called outgoing_orders: It shows how the actual destination, and the timestamp of the outgoing order.
So, the data could be:
--Incoming_orders:
Destination Timestamp
ROUTE B 14/03/2018 7:48:00
ROUTE A 14/03/2018 7:58:00
ROUTE A 14/03/2018 12:48:00
ROUTE C 14/03/2018 13:28:00
--Scheduled_Output
ROUTE A 14/03/2018 8:00:00
ROUTE A 14/03/2018 11:00:00
ROUTE A 14/03/2018 12:00:00
ROUTE A 14/03/2018 17:00:00
ROUTE B 14/03/2018 8:00:00
ROUTE B 14/03/2018 10:00:00
ROUTE B 14/03/2018 12:00:00
ROUTE C 14/03/2018 07:00:00
ROUTE C 14/03/2018 14:00:00
ROUTE C 14/03/2018 17:00:00
--Which would lead to the following outgoing_orders:
ROUTE A 14/03/2018 8:00:00
ROUTE B 14/03/2018 8:00:00
ROUTE C 14/03/2018 14:00:00
ROUTE A 14/03/2018 17:00:00
Now, I want to check that the incoming order of 07:58 to route A actually made it into the output cycle of 08:00 for route A. I was thinking of creating a table like this to show it:
Destination output moment expected_output actual_output diff
Route A 8:00 1 1 0
Route A 11:00 0 0 0
Route A 12:00 0 0 0
Route A 17:00 1 1 0
But the question is: How do I calculate that expected_output column? How do I group the incoming order to Route A of 12:48 to the 12:00-17:00 group? It should count all the orders between scheduled output moments, but I'm not sure how to accomplish that.
Could I perhaps CEIL, FLOOR or ROUND to the closest scheduled_output value? Or can I somehow do a BETWEEN row n and n+1 with a rowcount? Or is there another, easier way?