sql - Merge two tables with same column names, add counters -
i have 2 tables same columns, first column name , second count. merge these tables, each name appears added count of 2 tables:
table1: table2: result table: name count name count name count name1 1 name3 3 name1 1 name2 2 name4 4 name2 2 name3 3 name5 5 name3 6 name4 4 name6 6 name4 8 name5 5 name6 6
as of moment have created pretty ugly structure execute this, , would like know if possible results in more elegant way.
what have far (table1 test1 , table2 test2):
create table test1 ( name varchar(40), count integer); create table test2 ( name varchar(40), count integer); create table test3 ( name varchar(40), count integer); create table test4 ( name varchar(40), count integer); create table test5 ( name varchar(40), count integer); insert test4 (name, count) select * test1; insert test4 (name, count) select * test2; insert test3 (name , count) select t1.name, t1.count + t2.count test1 t1 inner join test2 t2 on t1.name = t2.name; select merge_db(name, count) test3; insert test5 (name, count) (select name, max(count) test4 group name); create function merge_db(key varchar(40), data integer) returns void $$ -- souce: http://stackoverflow.com/questions/1109061/insert-on-duplicate-update-postgresql begin loop -- first try update key update test4 set count = data name = key; if found return; end if;-- not there, try insert key -- if else inserts same key concurrently, -- unique-key failure begin insert test4(name,count) values (key, data); return; exception when unique_violation then-- nothing, , loop try update again end; end loop; end; $$ language plpgsql;
=> create table t1 (name text,cnt int); => create table t2 (name text,cnt int); => insert t1 values ('name1',1), ('name2',2), ('name3',3), ('name4',4); => insert t2 values ('name3',3), ('name4',4), ('name5',5), ('name6',6); => select name,sum(cnt) (select * t1 union select * t2 ) x group name order 1; name | sum -------+----- name1 | 1 name2 | 2 name3 | 6 name4 | 8 name5 | 5 name6 | 6 (6 rows)
Comments
Post a Comment