I have a following query:
WITH t as (
SELECT date_trunc(\'hour\', time_series) as trunc
FROM generate_series(\'2013-02-27 22:00\'::timestamp, \'2013-02-
Try:
WITH t as (
SELECT time_series as trunc
FROM generate_series('2013-02-27 22:00'::timestamp, '2013-02-28 2:00',
'1 hour') as time_series
)
SELECT DISTINCT ON(t.trunc) t.trunc, e.id
FROM t
JOIN event e
ON e.created < t.trunc
ORDER BY t.trunc, e.created DESC
If it is too slow - tell me. I will give you a faster query.
You ca mix a self join and windows functions
Simplifying I take this table with this sample values:
create table t ( a int, b int);
insert into t values
( 1, 1),
( 2, Null),
( 3, Null),
( 4, 2 ),
( 5, Null),
( 6, Null);
In your query a
is trunc_u
and b
is your id
.
The query is:
with cte as (
select
t1.a,
coalesce( t1.b, t2.b, 0) as b,
rank() OVER
(PARTITION BY t1.a ORDER BY t2.a DESC) as pos
from t t1
left outer join t t2
on t2.b is not null and
t2.a < t1.a
)
select a, b
from cte
where pos = 1;
And results:
| A | B |
---------
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 2 |
| 6 | 2 |