当前位置:网站首页>How to remove duplication in left join from a simple example

How to remove duplication in left join from a simple example

2022-06-22 01:15:00 Summer seven


1. Execute statement , establish 3 A watch

CREATE TABLE table_dev1 (
	id serial NOT NULL,
	devicecode text NULL, 		--  equipment id
	openflag int4 NULL 		 	--  Whether to start  1: start-up , 0: Not activated 
);

CREATE TABLE table_dev2 (
	id serial NOT NULL,
	devicecode text NULL, 		--  equipment id
	devicetype int4 NULL, 		--  Device type 
	vendor text NULL 			--  Name of manufacturer 
);

CREATE TABLE table_dev3 (
	id serial NOT NULL,
	devicecode text NULL, 		--  equipment id
	openflag int4 NULL, 		--  Whether to start  1: start-up , 0: Not activated 
	devicetype int4 NULL, 		--  Device type 
	vendor text NULL 			--  Name of manufacturer 
);



2. Insert data into table_dev1 & table_dev2

insert into table_dev1 (devicecode, openflag)values ('123', 1);
insert into table_dev1 (devicecode, openflag)values ('abc', 0);

insert into table_dev2 (devicecode, devicetype, vendor)values ('123', 100, ' Passerby ');
insert into table_dev2 (devicecode, devicetype, vendor)values ('123', 100, ' Passerby ');
insert into table_dev2 (devicecode, devicetype, vendor)values ('abc', 101, ' Unknown ');

Get table data
 Insert picture description here



3. Use left join Association table table_dev1 & table_dev1, And insert the data into the table table_dev3

1) Not to heavy

insert into table_dev3 (devicecode, openflag, devicetype, vendor) 
select t1.devicecode, t1.openflag, t2.devicetype, t2.vendor 
from table_dev1 t1 
left join 
table_dev2 t2  
on t1.devicecode = t2.devicecode 

Get the results >>
 Insert picture description here


2) duplicate removal

insert into table_dev3 (devicecode, openflag, devicetype, vendor) 
select t1.devicecode, t1.openflag, t2.devicetype, t2.vendor 
from table_dev1 t1 
left join 
(select t3.* from 
  (select devicecode,devicetype,vendor,row_number() over (partition by devicecode order by id desc) as rownum from table_dev2) t3 where t3.rownum = 1 ) t2  
 on t1.devicecode = t2.devicecode 

Get the results >>
 Insert picture description here

原网站

版权声明
本文为[Summer seven]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206212359322948.html