Last active
August 30, 2018 17:40
-
-
Save johnsnook/143d81d0bd6d4b213dda6f8c0a082962 to your computer and use it in GitHub Desktop.
Postgresql sql to get all dates in a range even if there's no date, filling it in
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| with days as ( | |
| select * | |
| from generate_series( | |
| (select min(created_at::date) from visits), | |
| (select max(created_at::date) from visits), | |
| '1 day' | |
| ) day | |
| ) | |
| select d.day, count(distinct v.ip) | |
| from days d | |
| left join visits v on v.created_at::date = d.day | |
| group by d.day | |
| order by d.day ; | |
| -- By hour | |
| with hours as ( | |
| select to_char(hour, 'YYYY-MM-DD HH24') as hour | |
| from generate_series( | |
| (select min(created_at) from visits), | |
| (select max(created_at) from visits), | |
| '1 hour' | |
| ) hour | |
| ) | |
| select (h.hour || ':00')::timestamp as hour, count(distinct v.ip) | |
| from hours h left join visits v on to_char(v.created_at, 'YYYY-MM-DD HH24') = h.hour | |
| group by h.hour | |
| order by h.hour ; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment