You've posted your code as a quotation. You should have posted it as </> preformatted text. See Wiki - how to post code on this forum.
I (and many others) gave up on tag history for things like hourly and daily reports. The historian doesn't inter/extrapolate to give you the edge count values. e.g., If you have a count value for 09:50 and one for 10:05 and ask for an aggregate function of 10:00 to 11:00 it will start its calculations on the 10:05 value. If you tried to manipulate the data by script to generate the 10:00 value you'd have the problem of how far back to go in history to ensure you got the previous value.
From my response to https://forum.inductiveautomation.com/t/includeboundingvalues-not-working/90821:
I found Historian OK for general trending and useful for checking back on what happened at a certain time. For anything like production reports I recommend doing your own history. We logged each machine with a gateway script running on the hour and every 15 minutes as well as on status change of the "running" tag. With columns for t_stamp, running, cycle count1, good parts count, SKU (recipe) and FirstOutAlarm we were able to generate excellent historical and realtime views.
1 A never-resetting counter.
More discussion: Save machine count on each change of run status - #16 by josborn.
Tag change scripting: Script about calculate the cumulative downtime - #25 by Transistor.
If you do this and also scheduled logging on the hour or every 15 minutes using gateway scheduled events then the SQL and reporting for any interval becomes very simple.