Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 15701

Records closest to the time

$
0
0

I need to get 2 records for each date that have time closest to some defined time

For example, this is table (real table has more data)

CREATE TABLE t1 (time DATE, some_data NUMBER);

And that table will have records like this

INSERT INTO t1 VALUES(TO_DATE('1.1.2024 08:08:08', 'dd.mm.yyyy hh24:mi:ss'), 1);INSERT INTO t1 VALUES(TO_DATE('1.1.2024 10:10:10', 'dd.mm.yyyy hh24:mi:ss'), 2);INSERT INTO t1 VALUES(TO_DATE('1.1.2024 15:15:15', 'dd.mm.yyyy hh24:mi:ss'), 3);INSERT INTO t1 VALUES(TO_DATE('1.1.2024 20:20:20', 'dd.mm.yyyy hh24:mi:ss'), 4);INSERT INTO t1 VALUES(TO_DATE('2.1.2024 09:09:09', 'dd.mm.yyyy hh24:mi:ss'), 5);INSERT INTO t1 VALUES(TO_DATE('2.1.2024 12:12:12', 'dd.mm.yyyy hh24:mi:ss'), 6);INSERT INTO t1 VALUES(TO_DATE('2.1.2024 16:16:16', 'dd.mm.yyyy hh24:mi:ss'), 7);

I would like to get 2 records for each date, first one closest to 8 and second closest to 20 hours. In this example result data would be

1.1.2024 08:08:08       11.1.2024 20:20:20       42.1.2024 09:09:09       52.1.2024 16:16:16       7

I tried do this using subqueries, but since my real usage has complex query (with joins, subselects and so on) I got lost in it rather quick.
Is there any good and clean way to accomplish this?
Thank you in advance


Viewing all articles
Browse latest Browse all 15701

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>