I have a Postgres table with following structure:
CREATE TABLE tb1 (
id integer,
name text,
date date,
time time without tz
);
CREATE TABLE tb2 (
id integer,
name text,
date date
);
I need to generate a 3rd table tb3 that will have column time_now with increment steps by 10 minutes. If tb1.time is not the same as tb3.time_now then b2.name is filled in. If tb1.time equals (or close by time_now) it is inserted into tb3.
Example:
tb1
1, xxxx, 2014-10-01, 08:20:00
2, yyyy, 2014-10-01, 08:40:00
tb2
1, zzzz, 2014-10-01
2, vvvv, 2014-10-01
3, eeee, 2014-10-01
3rd table should look like:
1, 08:00:00,zzzz -----> from tb2
2, 08:10:00,vvvv -----> from tb2
3, 08:20:00,xxxx -----> from tb1
4, 08:30:00,eeee -----> from tb2
5, 08:40:00,yyyy -----> from tb1
How to achieve this?
First build a table of desired times with
generate_series(). From 8:00 to 8:50 in my example.Join to tb1 on
time. Attach ascending numbers to empty slots withrow_number()(rn).Join
tb2to the remaining empty slots in ascending order.Use COALESCE to pick names from
tb1andtb2.Be wary about off-by-1 errors.
SQL Fiddle.
Aside: I would use none of those column names.
idandnameare not descriptive - never use those, be more specific.dateandtimeare basic type names.