I have the following table:
id start_date end_date status
----------------------------------------------------------------------
1a 2020-04-09 21:34:00.000 2020-04-13 15:46:52.000 green
1a 2020-04-13 15:46:52.000 2020-04-16 15:46:52.000 red
1a 2020-04-16 15:46:52.000 null yellow
2a 2020-04-09 20:33:00.000 2020-04-16 15:46:52.000 green
2a 2020-04-16 15:46:52.000 2020-04-21 15:46:52.000 red
2a 2020-04-21 15:46:52.000 null yellow
3a 2020-04-09 21:34:00.000 2020-04-09 22:34:00.000 green
3a 2020-04-09 22:34:00.000 2020-04-09 23:36:00.000 red
3a 2020-04-09 23:36:00.000 2020-04-09 23:38:00.000 yellow
3a 2020-04-09 23:38:00.000 null red
I am interested to count how many unique ids were in each state everyday between two time ranges. So I need to generate days between two time ranges as a starter. For example, item with id 1a
was green everyday from 2020-04-09 21:34:00.000
to 2020-04-13 15:46:52.000
and I need to count that.
Edit:
The most important thing is that if one item changes several states on the same day, I need to count it only once for the most recent state on a day. For example, item with id 3a
changed states several times on 2020-04-09
. However, I only care about the most recent state which is red (on 2020-04-09 23:38:00.000
). This is to make sure that I don't artificially inflate the data.
My desired output is this:
day state total ids
2020-04-09 green 2 [1a, 2a]
2020-04-09. yellow 0 []
2020-04-09. red 1 [3a]
2020-04-10. green 2 [1a, 2a]
2020-04-10. yellow 0 []
.....etc
I have this query:
select serie.day as time,
a.state,
count(a.start_date) as total,
a.id
from (
SELECT date_series::date AS day
FROM generate_series(
'2020-04-09 00:00:00.000'::date,
'2020-04-24 15:22:22.000',
'1 day'
) AS date_series
) as serie
left join event_entries a on a.start_date::date = serie.day::date
group by serie.day, a.state, a.id order by time
But it only records the total # ids per state on the start_date and nothing in between. How can I refactor this query to produce the desired result?
Here is the fiddle