Skip to content
Advertisement

Database Query to generate a Time-based Chart

I have a logins table in the following (simplified) structure:

Now I want to generate chart like this:

https://prnt.sc/mifz6y

Basically I want to show the logins within the past 48 hours.

My current query:

This works as long as there are entries for every hour. However, if in some hour there were no logins, there will be no entry selected, like this:

I would need a continous query, so that I can simply put the count values into an array:

Based on that I can simply transform the query result into an array like [1, 2, 0, 3, 5] and pass that to my frontend.

Is this possible with postgresql? Or do I need to implement my own logic?

Advertisement

Answer

This can almost certainly be tidied up a bit but should give you some ides. Props to clamp for the generate_series() tip :

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement