I have the following table:
create table foobar (
account_id bigint not null,
timestamp timestamp not null,
balance_one numeric not null,
balance_two numeric not null,
primary key (timestamp, account_id)
);
I have a given time range with BEGIN
and END
. Within that range, a series of timestamps is generated with a given step size, starting at the lower bound. Let's call those timestamps "interval boundaries".
I want to select all rows within the given time range with a timestamp closer than any other to one of the generated timestamps in the series.
The general part of the query is pretty simple, select rows within the given time range:
select * from foobar
where account_id = ?
and timestamp between {BEGIN} and {END}
order by timestamp asc;
The part I don't understand, is how to trim my result set to only the rows closest to the interval boundaries.
Example data:
account_id | timestamp | balance_one | balance_two |
---|---|---|---|
1 | 28 June 2021 17:00:00 | 0.0 | 0.0 |
1 | 28 June 2021 17:00:05 | 1.0 | 0.0 |
1 | 28 June 2021 17:00:10 | 0.5 | 0.0 |
1 | 28 June 2021 17:00:15 | 0.0 | 1.0 |
1 | 28 June 2021 17:00:20 | 0.5 | 0.0 |
1 | 28 June 2021 17:00:25 | 1.0 | 1.0 |
2 | 28 June 2021 17:00:00 | 0.0 | 0.0 |
2 | 28 June 2021 17:00:05 | 1.0 | 7.0 |
2 | 28 June 2021 17:00:07 | 2.0 | 6.0 |
2 | 28 June 2021 17:00:15 | 3.0 | 5.0 |
2 | 28 June 2021 17:00:20 | 4.0 | 4.0 |
2 | 28 June 2021 17:00:25 | 5.0 | 3.0 |
2 | 28 June 2021 17:00:30 | 6.0 | 2.0 |
2 | 28 June 2021 17:00:35 | 7.0 | 1.0 |
Example queries with params:
ID = 1, BEGIN = 28 June 2021 17:00:00, END = 28 June 2021 17:00:30, INTERVAL = 10 seconds
Result:
account_id | timestamp | balance_one | balance_two |
---|---|---|---|
1 | 28 June 2021 17:00:00 | 0.0 | 0.0 |
1 | 28 June 2021 17:00:10 | 0.5 | 0.0 |
1 | 28 June 2021 17:00:20 | 0.5 | 0.0 |
1 | 28 June 2021 17:00:25 | 1.0 | 1.0 |
ID = 2, BEGIN = 28 June 2021 17:00:00, END = 28 June 2021 17:00:30, INTERVAL = 10 seconds Result:
account_id | timestamp | balance_one | balance_two |
---|---|---|---|
2 | 28 June 2021 17:00:00 | 0.0 | 0.0 |
2 | 28 June 2021 17:00:10 | 2.0 | 6.0 |
2 | 28 June 2021 17:00:20 | 4.0 | 4.0 |
2 | 28 June 2021 17:00:30 | 6.0 | 2.0 |
0
, incrementing in intervals of say5
, I want the record with timestamp closest to the interval timestamps – vddox