Hey I'm trying to insert or update(if the constraints are duplicated) based on a query result, these are the create table statement:
CREATE TABLE IF NOT EXISTS public.inventory (
inventory_id serial PRIMARY KEY,
arrive_date date NOT NULL,
arrive_location character varying NOT NULL,
thing_type integer NOT NULL,
quantity integer NOT NULL
);
CREATE TABLE IF NOT EXISTS public.preprocess_things (
preprocess_id serial PRIMARY KEY,
arrive_date date NOT NULL,
arrive_location character varying NOT NULL,
data jsonb NOT NULL,
CONSTRAINT preprocess_things_arrive_date_arrive_location_bo_key UNIQUE (arrive_date, arrive_location)
);
This is the upsert query:
WITH result_query AS (
SELECT DATE_TRUNC('day', arrive_date) AS date,
arrive_date,
arrive_location,
thing_type,
SUM(quantity) AS total_things
FROM inventory
GROUP BY date, arrive_location, thing_type
)
INSERT INTO preprocess_things (
arrive_date,
arrive_location,
data
)
SELECT r.date AS arrive_date,
r.arrive_location,
jsonb_build_object(r.thing_type, r.total_things)
FROM result_query r
ON CONFLICT (arrive_date, arrive_location) DO
UPDATE SET data = preprocess_things.data || EXCLUDED.data
The result_query rows are:
date | arrive_location | thing_type | thing_count
2018-05-30 00:00:00-00 | location_00 | 3 | 2
2018-05-31 00:00:00-00 | location_00 | 3 | 8
2018-05-31 00:00:00-00 | location_00 | 4 | 7
Trying to insert in preprocess_things, where data is a jsonb type and expected result is:
id | arrive_date | arrive_location | data
1 | 2018-05-30 00:00:00-00 | location_00 | { "3": 2 }
2 | 2018-05-31 00:00:00-00 | location_00 | { "3": 8, "4": 7 }