I am writing a statistics-based application from a SQLite database. There is a table in which user input and output are recorded (SessionStart, SessionEnd DateTimes).
What I'm looking for is a query that can show how many hours a user has been logged in as a line graph, so 60 users were logged in between 12:00 and 1:00 AM (at any time), between 1: 00 and 2:00 AM 54 users were registered, etc.
And I want to be able to run SUM from this, so I cannot bring entries to .NET and iterate over them that way.
I came up with a rather primitive approach, a subquery for every hour of the day, however this approach turned out to be slow and slow. I need to be able to calculate this in a couple of hundred thousand records per second.
SELECT
case
when (strftime('%s',datetime(date(sessionstart), '+0 hours')) > strftime('%s',sessionstart)
AND strftime('%s',datetime(date(sessionstart), '+0 hours')) < strftime('%s',sessionend))
OR (strftime('%s',datetime(date(sessionstart), '+1 hours')) > strftime('%s',sessionstart)
AND strftime('%s',datetime(date(sessionstart), '+1 hours')) < strftime('%s',sessionend))
OR (strftime('%s',datetime(date(sessionstart), '+0 hours')) < strftime('%s',sessionstart)
AND strftime('%s',datetime(date(sessionstart), '+1 hours')) > strftime('%s',sessionend))
then 1 else 0 end as hour_zero,
... hour_one,
... hour_two,
........ hour_twentythree
FROM UserSession
I am wondering what is the best way to determine if two DateTimes have seen in a certain hour (best scenario, how many times did it cross an hour if it was registered in a few days, but not necessarily)?
The only other idea that I had was a “hour” table specific to this, and just counting the hours that the user saw at runtime, but I feel this is more of a hack than the previous SQL.
Any help would be greatly appreciated!