I have a table like:
create table movement_logs (
id integer NOT NULL,
room_id integer NOT NULL,
entry_time timestamp NOT NULL,
exit_time timestamp,
user_id integer NOT NULL
)
This models a domain where users enter rooms. This table logs timestamps when users enter and leave rooms.
I want query for the time windows where most users were in a room. I am using Postgres. Can this be done in SQL?
2
Answers
Yes, this is possible in SQL.
See example.
Query result
A slightly different approach would be the usage of the range data type, tsrange. When you have an entry time and exit time, this would be beneficial to your data model and application because of the potential constraints, operators and indexes you could use.
The function tsrange() makes the ranges for you, and could leave the lower or upper range NULL. The operator && looks for overlapping ranges and generate_series() creates the different time windows you want to measure. In this example I use an interval of 15 minutes, you could change this to some other value.